(* File: gnuplot_unix.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_unix.ml,v 1.4 2004-11-28 23:49:39 chris_77 Exp $	 *)

(*
 * Configuration
 ***********************************************************************)

(* The gnuplot program.  The default should be fine for most people. *)
let gnuplot = "gnuplot"

(***********************************************************************)

open Gnuplot_dir

type t = {
  dir : string;
  file : bool;
  mutable no : int; (* temporary file number *)
}

let temp_dir = try Unix.getenv "TMPDIR" with Not_found -> "/tmp"

let open_gnuplot_out persist ?pos xsize ysize color =
  (* The -geometry,... options have no influence if the terminal is
     not X11 (so no need to take special care about X11). *)
  let pos =
    match pos with
    | None -> ""
    | Some (x,y) -> Printf.sprintf "%+i%+i" x y in
  let pgm =
    Printf.sprintf "%s -noraise -geometry %.0fx%.0f%s %s %s" gnuplot
      xsize ysize pos (if persist then "-persist" else "")
      (if color then "" else "-gray") in
  let gp = Unix.open_process_out pgm in
  (* On sucessful opening of a pipe to gnuplot, create a temp dir to
     hold data files. *)
  (gp, { dir = mk_temp_dir temp_dir "gp" ".dir"; file = false; no = 0 })

let open_file_out fname =
  let gp = open_out fname in
  (gp, { dir = mk_temp_dir temp_dir "gp" ".dir"; file = true; no = 0 })


let close_out gp t =
  if t.file then
    (* If we were writing the commands to a file, the data files must
       be kept -- otherwise the file is unusable. *)
    close_out gp
  else
    match Unix.close_process_out gp with
    | Unix.WEXITED 0 -> remove_rec_dir t.dir
    | _ -> raise (Sys_error "Gnuplot ended with an error")


let set_terminal_X =
  let pgmname = Filename.basename Sys.argv.(0) in
  fun g _ _ _ ->
    Printf.fprintf g "set terminal x11 title \"OCaml Gnuplot: %s\"\n" pgmname

let open_temp_file t =
  t.no <- t.no + 1;
  let fname = Filename.concat t.dir (string_of_int t.no ^ ".dat") in
  (fname, open_out fname)
