let main () =
  Arg.parse options
    (fun s ->
      match !in_file with
        None -> in_file := Some s;
      | Some f -> failwith usage
    )
    (usage^"where options are:");
  let in_file =
    match !in_file with
      None -> failwith usage
    | Some f -> f
  in
  let out =
    match !out_file with
      None -> stdout
    | Some file -> open_out file
  in
  begin
    match !mode with
      Gencode ->
        let db = Dbf_sql_io.db_of_file in_file in
        (* sort columns by name in tables *)
        let comp_cols c1 c2 =
          Pervasives.compare
            (String.lowercase c1.col_name)
            (String.lowercase c2.col_name)
        in
        let sort_cols_in_table ta =
         ta.ta_columns <- List.sort comp_cols ta.ta_columns
        in
        List.iter sort_cols_in_table db.db_tables;

        flush stdout;
        if List.exists (fun t -> t.ta_logged) db.db_tables then
          begin
            Printf.fprintf out "\nlet log_who : (unit -> Dbf_sql_misc.log_who) ref = ref (fun () -> 0)\n\n";
            output_string out
            "let who_modified_what =
  let rec iter acc current = function
    [] -> List.rev acc
  | [id,d,ac,_] -> List.rev ((id,d,ac,current) :: acc)
  | (id1,d1,ac1,_)::(id2,d2,ac2,t2)::q ->
    iter ((id1,d1,ac1,t2)::acc) current ((id2,d2,ac2,t2)::q)
  in
  let comp (_,(d1:float),_,_) (_,(d2:float),_,_) = compare d1 d2 in
  fun current l -> iter [] current (List.sort comp l)
"
;
          end;

        List.iter
        (fun table ->
          let idxes = indexes_of_table table db.db_indexes in
          let module_name =
            match !remove_table_prefix with
              None -> String.capitalize table.ta_name
            | Some s ->
                String.capitalize
                  (remove_prefix s table.ta_name)
          in
          Dbf_sql_gen.print (table, module_name, idxes) out)
        db.db_tables;
      List.iter
        (fun vtable ->
          let idxes = indexes_of_vtable vtable db.db_indexes in
          Dbf_sql_vgen.print (vtable, idxes) out)
          db.db_vtables;
        Printf.fprintf out
          "\nmodule Queries = functor (Sql : Dbf_sql_driver.SqlDriver) -> struct\n";
        List.iter
        (fun query ->
          Dbf_sql_qgen.print query out)
          db.db_queries;
        Printf.fprintf out "end\n"
    | Convert t ->
        let db = convert_from_old in_file t in
        output_string out (Xml.to_string_fmt (Dbf_sql_io.xml_of_db db))
  end;
  close_out out