let gcc_cmd = Printf.sprintf "%s -shared" !Clflags.c_linker
let rm_cmd = "rm -f"

(* plugin-cnt -> modulename, .so fname *)
let make_so basecnt =
  let prefixname = "./plugin" ^ string_of_int basecnt in 
  let modulename = String.capitalize(Filename.basename prefixname) in
  let outname = prefixname ^ ".so" in
  let objname = prefixname ^ ".o" in
  let cmd = gcc_cmd ^ " -o " ^ outname ^ " " ^ objname in
  let () = if !Clflags.verbose then Printf.printf "About to run: %s\n" cmd in
  let _ = assert (Sys.command cmd = 0) in
  (modulename,outname)

let rm_plugin basecnt =
  let prefixname = "./plugin" ^ string_of_int basecnt in 
  let outname = prefixname ^ ".so" in
  let objname = prefixname ^ ".o" in
  let cmxname = prefixname ^ ".cmx" in
  let cminame = prefixname ^ ".cmi" in
  let cmd = rm_cmd ^ " " ^ outname^ " " ^ objname ^ " " ^ cmxname ^ " " ^ cminame
  in assert (Sys.command cmd = 0)

(* the entry point has the form of camlCodexxx__entry
   gleaned from the .s file
*)

let load_and_run cnt outname modulename =
  let entry_point = "caml" ^ modulename ^ "__entry" in
  let _ = Natdynlink.loadfile outname entry_point in
  rm_plugin cnt;
  !Trx.execute_expression_result 

let () = begin 
  (* Trx.native_mode := true; *)
  (* Trx.execute_expression_hook := execute_expression_native; *)

  (* Need this to force the loading of driver/optcompile.ml *)
  Optcompile.init_path();

  Trx.load_compiled_code_hook :=
    (fun cnt -> 
      let () = if !Clflags.verbose then Printf.printf "Got cnt %d\n" cnt in
      let (modulename,outname) = make_so cnt in
      let () = if !Clflags.verbose then Printf.printf "compiled, module %s\n" modulename in
      let _ = load_and_run cnt outname modulename in
      ())
end;;
