(* File: gnuplot_macos.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_macos.ml,v 1.5 2007-11-27 23:07:22 chris_77 Exp $	 *)

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

(* The gnuplot program. *)
let gnuplot = "gnuplot"

(* If one wants the 'aqua' terminal instead of the X11 one on MacOS X. *)
let macosX_aqua = true

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

open Printf
open Gnuplot_dir

let macosX =
  match Sys.os_type with
  | "Unix"  -> true
  | "MacOS" -> false
  | _ ->
      output_string stderr "Configure PLATFORM in Makefile.conf";
      exit 1

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

let temp_dir =
  if macosX then
    try Unix.getenv "TMPDIR" with Not_found -> "/tmp"
  else
    try Sys.getenv "TempFolder" with Not_found -> ":"


let open_gnuplot_out =
  fun persist ?pos xsize ysize color ->
    let pos =
      match pos with
      | None -> ""
      | Some (x,y) -> sprintf "%+i%+i" x y in
    let pgm =
      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
    (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
    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 =
  if macosX_aqua then begin
    let pgmname = Filename.basename Sys.argv.(0) in
    fun g xsize ysize color ->
      fprintf g "set terminal aqua title \"%s\" size %.0f %.0f\n"
        pgmname xsize ysize
  end
  else
    (* X11 gnuplot under MacOS X *)
    let pgmname = Filename.basename Sys.argv.(0) in
    fun g _ _ _ ->
      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)

