(***********************************************************************)
(*                                                                     *)
(*                           The V6 Engine                             *)
(*                                                                     *)
(*          Francois Rouaix, projet Cristal, INRIA Rocquencourt        *)
(*                                                                     *)
(*  Copyright 1996 Institut National de Recherche en Informatique et   *)
(*  Automatique.  Distributed only by permission.                      *)
(*                                                                     *)
(***********************************************************************)

(* $Id: msys.ml,v 1.1 1996/10/22 13:12:51 rouaix Exp $ *)

open Printf
open Unix


(* Tilde substitution *)

(* skip to next / *)
let rec next_slash s n =
  if  n >= String.length s or s.[n] = '/' 
  then n
  else next_slash s (succ n)

let tilde_subst s =
 try
  if s = "" or s.[0] <> '~' then s 
  else
    let len = String.length s in
    if len = 1 then Sys.getenv "HOME"
    else match s.[1] with
      '/' -> 
        Filename.concat (Sys.getenv "HOME") (String.sub s 2 (len - 2))
     | _ ->
       let final = next_slash s 1 in
       let user = String.sub s 1 (pred final) in
       let pwnam = getpwnam user in
         if succ final >= len then pwnam.pw_dir
         else
          Filename.concat pwnam.pw_dir 
               (String.sub s (succ final) (len - (succ final)))
 with
    Unix_error(_,_,_) -> s
  | Sys_error _ -> s
  | Not_found -> s

(* Quiet unlink *)
let rm s = try unlink s with Unix_error _ -> ()

let fsize f =
  try (Unix.stat f).st_size
  with Unix_error(_,_,_) -> raise Not_found

let tmp_dir = ref "/tmp"
let mktemp =
  let cnter = ref 0 
  and pid = Unix.getpid() in
  (function prefx -> 
      incr cnter; 
      (Filename.concat !tmp_dir
      	 (prefx^string_of_int pid^"."^string_of_int !cnter)))


