#!/bin/sh
exec lush "$0" "$@"
!#

;; Usage: tex2png blah.tex blah.png
;; This converts a piece of latex to a 300dpi 
;; PNG image with transparent background

(defvar convert-cmd "convert")

(de latex-head ()
  `("\\documentclass{article}"
    "\\usepackage{color,epsfig}"
    ;; "\\usepackage{pstricks,pst-node,pst-text,pst-3d,multirow}"
    ))

(de latex-macros (rf gf bf rb gb bb)
  `(,(concat "\\definecolor{fg}{rgb}" 
	     (sprintf "{%5.3f,%5.3f,%5.3f}" (/ rf 255) (/ gf 255) (/ bf 255)))
    ,(concat "\\definecolor{bg}{rgb}" 
	     (sprintf "{%5.3f,%5.3f,%5.3f}" (/ rb 255) (/ gb 255) (/ bb 255)))
    "\\pagestyle{empty}"
    "\\pagecolor{bg}"
    "\\begin{document}"
    "\\color{fg}"))

(de latex-tail ()
  `("\\end{document}"))

  
(de ps2png (in out &optional (bg-r 255) (bg-g 255) (bg-b 255) (res 300) (border 4))
  (sys (sprintf "convert -units PixelsPerInch -density %d -trim -border %dx%d -bordercolor rgb\\(%d,%d,%d\\) -matte -transparent rgb\\(%d,%d,%d\\) -type PaletteMatte %s %s" 
	        res border border bg-r bg-g bg-b bg-r bg-g bg-b in out)))

(de ps2djvu (in out)
  (sys (sprintf "djvudigital --dpi=300 --bg-subsample=1 --words %s %s" in out)))

(de latex2png (in out &optional (rf 0) (gf 0) (bf 0) (rb 255) (gb 255) (bb 255))
  (let* ((filefull (tmpname))
	 (filebase (basename filefull))
	 (texdir (dirname filefull))
	 (texfile (concat filebase ".tex"))
	 (auxfile (concat filebase ".aux"))
	 (logfile (concat filebase ".log"))
	 (dvifile (concat filebase ".dvi"))
	 (psfile (concat filebase ".ps"))
	 (pngfile (concat filebase ".png")))
    (when (stringp in) 
      (when (= in "-") (setq in "$stdin"))
      (setq in (read-lines in)))
    (writing (concat texdir "/" texfile) 
      (write-lines (latex-head))
      (when (filep (concat (getenv "HOME") "/etc/macros.tex"))
	(printf "\\input{%s}\n" (filename-chop-suffix (concat (getenv "HOME") "/etc/macros.tex"))))
      (write-lines (latex-macros rf gf bf rb gb bb))
      (write-lines in)
      (write-lines (latex-tail)))
    (pushd texdir)
    (repeat 2 (sys (sprintf "latex %s" texfile)))
    (sys (sprintf "dvips %s -o %s" dvifile psfile))
    (ps2png psfile pngfile rb gb bb)
    (rm texfile)
    (rm dvifile)
    (rm auxfile)
    (rm logfile)
    (rm psfile)
    (popd)
    (sys (concat "mv " texdir "/" pngfile " " out))
    in))

(setq verbose t)
(de debugv s (when verbose (writing "$stderr" (apply printf s))))

(setq show ())

(when (not donotrun) 
  (libload "libimage/image-io")
  (let* ((in (cadr argv))
	 (out (caddr argv))
	 (in (latex2png in out 0 0 0 255 255 255))
	 (pngim (image-read-rgba out)))
    ;; (printf "%s\n" out)
    (when show
      (ogre)
      (setq win 
	    (new autowindowobject 10 10 100 100 "tex2png"
		 (new column
		      (setq editor (new edittext 40 8))
		      (setq view (new ogrimage pngim)))))
      (==> editor setdata in)
      (wait win))))

	



