(***********************************************************************)
(*                                                                     *)
(*                           Objective Caml                            *)
(*                                                                     *)
(*            François Pessaux, projet Cristal, INRIA Rocquencourt     *)
(*            Pierre Weis, projet Cristal, INRIA Rocquencourt          *)
(*            Jun Furuse, projet Cristal, INRIA Rocquencourt           *)
(*                                                                     *)
(*  Copyright 1999,2000,2001,2002,2001,2002                            *)
(*  Institut National de Recherche en Informatique et en Automatique.  *)
(*  Distributed only by permission.                                    *)
(*                                                                     *)
(***********************************************************************)

(* temporary directory *)
let tmp_dir = 
  ref (try Sys.getenv "CAMLIMAGESTMPDIR" with Not_found -> "/tmp")

let cnter = ref 0

let new_tmp_file_name prefx =
  if not (Sys.file_exists !tmp_dir) then 
    raise (Failure ("Temporary directory " ^ !tmp_dir ^ " does not exist"));
  let rec fname () =
    incr cnter;
    let name =
      Filename.concat !tmp_dir (Printf.sprintf "camlimages-%s-%d" prefx !cnter)
    in
    if not (Sys.file_exists name) then name
    else begin
      prerr_endline ("Warning: tmp file "^name^" already exists");
      fname ()
    end
  in
  let f = fname () in
  at_exit (fun () -> try Sys.remove f with _ -> ());
  f
