(* Generation of [lib/config.h] *)

#load "str.cma";;

open Format
open Str

let (|>) x f = f x (* for OCaml 4.00 or below *)

(** [gprintf filename fmt ...] generates a file and prints [printf]-style
    formatted string. *)
let gprintf filename fmt =
  let gen_file s () =
    let oc = open_out filename in
    output_string oc s;
    close_out oc
  in
  ksprintf gen_file fmt

let fold_lines f init filename =
  let ic = open_in filename in
  let rec aux acc = try aux (f acc (input_line ic)) with End_of_file -> acc in
  let acc = aux init in
  close_in ic;
  acc

(** [parse_version str] parses [str] as a version number.
    @return [Some (major, minor, micro)] if the form of [str] is
    ["major.minor.micro"]. Otherwise, [None] is returned. *)
let parse_version =
  let get_int i s = matched_group i s |> int_of_string in
  let r = regexp "^\\([0-9]+\\)\\.\\([0-9]+\\)\\(\\.\\([0-9]+\\)\\)?" in
  fun s ->
    match string_match r s 0 with
    | false -> None
    | true ->
      let micro = try get_int 4 s with Not_found -> 0 in
      Some (get_int 1 s, get_int 2 s, micro)

let () =
  match parse_version Sys.ocaml_version with
  | None -> failwith "Sys.ocaml_version has invalid format"
  | Some (major, minor, micro) ->
    gprintf "lib/config.h"
      "/* This file is automatically generated by gen_files.ml */@\n\
       @\n\
       /* OCaml version */@\n\
       #define OCAML_MAJOR %d /* The major version of OCaml */@\n\
       #define OCAML_MINOR %d /* The minor version of OCaml */@\n\
       #define OCAML_MICRO %d /* The patchlevel of OCaml */@."
      major minor micro ()

