(* File: gnuplot_dir.ml

   Copyright (C) 2001-2004

     Christophe Troestler
     email: Christophe.Troestler@umh.ac.be
     WWW: http://math.umh.ac.be/an/software/

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public License
   version 2.1 as published by the Free Software Foundation, with the
   special exception on linking described in file LICENSE.

   This library is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the file
   LICENSE for more details.
*)
(* 	$Id: gnuplot_dir.ml,v 1.3 2004-11-28 23:49:39 chris_77 Exp $	 *)

open Printf

let prng = Random.State.make_self_init ()

let mk_temp_dir temp_dir prefix suffix =
  let rec try_name counter =
    if counter >= 1000 then
      invalid_arg (sprintf "Gnuplot.mk_temp_dir: %S dir nonexistent or full"
                     temp_dir);
    let rnd = (Random.State.bits prng) land 0xFFFFFF in
    let name = Filename.concat temp_dir
                 (sprintf "%s%06x%s" prefix rnd suffix) in
    try
      Unix.mkdir name 0o700;
      name
    with Unix.Unix_error _ -> try_name (counter + 1) in
  try_name 0

(* [remove_rec_dir d] remove recursively the dir (or file) [d].
   Errors are ignored.  *)
let remove_rec_dir =
  let rec rm dirname =
    match (Unix.stat dirname).Unix.st_kind with
    | Unix.S_DIR -> (* Remove the content of the dir recursively *)
        let d = Unix.opendir dirname in
        begin try
          while true do
            match Unix.readdir d with
            | "." | ".." -> ()
            | f -> rm (Filename.concat dirname f)
          done
        with End_of_file -> ()
        end;
        Unix.closedir d;
        Unix.rmdir dirname
    | _ ->
        Unix.unlink dirname in
  fun dirname ->
    try rm dirname
    with _ -> ()

(* let remove_rec_dir d = Printf.eprintf "temp dir = %S\n" d (\* DEBUG *\) *)
