#!/usr/bin/python
#This sample script reads a template file (demo1.tpl), inserts
#   values from the user interface and converts the reulting
#   RLPlot file to portable network graphics. This script invokes
#   the exprlp utility to convert from RLPlot format to encapsulated
#   postscript, and ghostscript to convert *.eps to *.png.
#Author: R. Lackner, (c)2002-2008

import cgi, os, popen2, sys
from string import *

print"Content-Type: image/png"
print
val1, val2, val3 = ('100', '300', '200')
#get variables from CGI-interface
form = cgi.FieldStorage()
keys = form.keys()
if keys:
   for key in keys:
      if(key == "val1"): val1 = form[key].value
      elif(key == "val2"): val2 = form[key].value
      elif(key == "val3"): val3 = form[key].value

#create rlplot file from template
f1 = open("/tmp/rlpdemo1.rlp", "w")
f = open("demo1.tpl")
while 1:
   line = f.readline()
   if not line: break
   line=replace(line, "{val1}", val1)
   line=replace(line, "{val2}", val2)
   line=replace(line, "{val3}", val3)
   f1.write(line)
f.close()
f1.close()

#create encapsulated PostScript from rlplotfile
os.system("exprlp -eq /tmp/rlpdemo1.rlp /tmp/rlpdemo1.eps")

#appen "quit" to the file for gs to exit after conversion
append = "\nquit\n"
f = open("/tmp/rlpdemo1.eps", "a")
f.write(append)
f.close()

#convert PostScript to PNG
os.system("gs -dNOPAUSE -sDEVICE=png16 -r100 -q -g630x434 -sOutputFile=/tmp/rlpdemo1.png /tmp/rlpdemo1.eps")

#copy PNG file to stdout
f = open("/tmp/rlpdemo1.png")
buffsize=1024
while 1:
   line =f.read(buffsize)
   if not line: break
   sys.stdout.write(line)
f.close()