(*
  
    This snippet of code illustrates how to call an XQuery function 
    from ML. 

 *)

let example1 () =
  try 
    (* Load an XQuery "context" file, which contains an XQuery prolog: 
       imported schema and namespaces and user-defined functions *)

    let context = Galapi.build_context_from_file "xq-example1.xq" in

    (* Construct an XML value from an XML document, which can be
       passed as an argument to an XQuery function. *)

    let xmldoc = Galapi.load_document "xml-example.xml" in

    (* Construct some XML values from CAML primitive values. *)

    let xmlint = Galapi.xml_of_int 1 in
    let xmlstr = Galapi.xml_of_string "a string" in
    let xmlflt = Galapi.xml_of_float 3.14 in

    (* Call the XQuery function "to_html", and pass it four arguments: *)
    let res = Galapi.eval_xquery_fun context "to_html" [xmldoc; xmlint; xmlstr; xmlflt] in 

    (* Serialize the result to stdout *)
    Galapi.serialize_to_output_channel stdout res

  with

    (* Any errors raised by Galax are printed to stderr *)
    | exn -> Error.printf_error "" exn


(* The second example features binding a variable from the Caml side *)
let example2 () =
  try 
    (* Load an XQuery "context" file, which contains an XQuery prolog: 
       imported schema and namespaces and user-defined functions *)

    let context = Galapi.build_context_from_file "xq-example2.xq" in

    (* Construct an XML value from an XML document, which can be
       passed as an argument to an XQuery function. *)
    
    let xmldoc = Galapi.load_document "xml-example.xml" in
    
    let ext_var = Galapi.unresolved_qname_of_string "ext" in

    let context' = Galapi.add_variable_binding_to_context context ext_var xmldoc in

    (* Construct some XML values from CAML primitive values. *)
    
    let xmlint = Galapi.xml_of_int 1 in
    let xmlstr = Galapi.xml_of_string "a string" in
    let xmlflt = Galapi.xml_of_float 3.14 in
    
    (* Call the XQuery function "to_html", and pass it four arguments: *)
    let res = Galapi.eval_xquery_fun context' "to_html" [xmldoc; xmlint; xmlstr; xmlflt] in 
    
    (* Serialize the result to stdout *)
    Galapi.serialize_to_output_channel stdout res
      
  with
    
    (* Any errors raised by Galax are printed to stderr *)
  | exn -> Error.printf_error "" exn
	
let _ =
  example1 ();
  example2 ()

