;;
;; Use Gnuplot to plot diagrams
;;

(define (splot-cell fp buf row col)
  (if (= (get-type buf row col) EXPRESSION)
    (writes fp (get-cell row col) "\n")
    (writes fp "0\n")))

(define (splot style)
  (let ((has-tics nil) (has-titles nil)
	(pid 0)
	(c 0) (c1 0) (c2 0) (r 0) (r1 0) (r2 0)
	(fn-cmd "") (fn-output "") (fn-data "")
	(fp-cmd nil) (fp-output nil) (fp-data nil))
    (set! pid (number->string (getpid) 10))
    (set! fn-cmd (string-append "/tmp/siagplot" pid ".cmd"))
    (set! fn-output (string-append "/tmp/siagplot" pid ".ps"))
    (set! fp-cmd (fopen fn-cmd "w"))
    (writes fp-cmd "# This file is used by Siag to control Gnuplot\n")
    (writes fp-cmd "set terminal postscript\n")
    (writes fp-cmd "set output \"" fn-output "\"\n")
    (writes fp-cmd "set data style " style "\n")
    (writes fp-cmd "set noparametric\n")
    (set! r0 (position-row (get-blku)))
    (set! r1 r0)
    (set! r2 (position-row (get-blkl)))
    (set! c0 (position-col (get-blku)))
    (set! c1 c0)
    (set! c2 (position-col (get-blkl)))
    (set! fn-data (string-append "/tmp/siagplot" pid "." (number->string r 10)))
    (set! fp-data (fopen fn-data "w"))
    (writes fp-cmd "splot \"" fn-data "\"\n")
    (set! r r1)
    (while (<= r r2)
      (set! c c1)
      (while (<= c c2)
	(splot-cell fp-data nil r c)
	(set! c (+ c 1)))
      (writes fp-data "\n")
      (set! r (+ r 1)))
    (fclose fp-data)
    (writes fp-cmd "\n")
    (fclose fp-cmd)
    (system "gnuplot " fn-cmd)
    (spawn (string-append viewer-command " -landscape " fn-output))))
;    (spawn (string-append "ghostview -landscape " fn-output))))

