(* Miscellaneous functions. *)

let flag_verbose = ref false

let get_root_directory () =
  try
    Sys.getenv "ACCOUNTS_ROOT"
  with Not_found -> Sys.getcwd ()

let fail msg =
  prerr_endline msg;
  exit 1

let open_config_file leafname =
  let path = (get_root_directory ()) ^ "/config/" ^ leafname in
  try
    open_in path
  with Sys_error msg ->
    fail ("Error whilst opening config file " ^ path ^ ":\n  " ^ msg)

let open_config_file_fail_ok leafname =
  let path = (get_root_directory ()) ^ "/config/" ^ leafname in
  try
    open_in path
  with Sys_error msg -> raise Not_found

let round amount = (float_of_int (truncate (amount *. 100.0))) /. 100.0
let format_money sum =
  (* Note: don't use just "sum / 100" to get the minus sign, because
     when sum is zero, any minus won't appear.  *)
  let s = Printf.sprintf "%d.%02d" (abs (sum / 100)) (abs (sum mod 100)) in
    if sum < 0 then "-" ^ s else s

let verbose str =
  if !flag_verbose then print_endline str
                   else ()

let iter_files dir f =
  let path = (get_root_directory ()) ^ "/" ^ dir in
  let dir = Unix.opendir path in
  try
    while true do
      let name = Unix.readdir dir in
        if String.get name 0 <> '.' then
        begin
          verbose ("iter_initial_files: name=" ^ name);
          let channel = open_in (path ^ "/" ^ name) in
            (f name channel; close_in channel)
        end
        else ()
    done
  with End_of_file ->
    Unix.closedir dir

