#!/usr/bin/env python

import sys, os.path, tempfile, shutil

if len(sys.argv) != 2: sys.exit('usage: '+sys.argv[0]+' filename.chpl')
(s0, ext) = os.path.splitext(sys.argv[1]);
if ext!='.chpl': sys.exit('usage: '+sys.argv[0]+' filename.chpl')

cwd = os.getcwd()

filename = os.path.basename(s0);
tmpdir = tempfile.mkdtemp()
latexfile = tmpdir+'/'+filename+'.tex'
realfile = os.path.realpath(sys.argv[1])
chpl_home = os.getenv('CHPL_HOME')
if chpl_home==None:
    sys.exit('Please set the CHPL_HOME environment variable.')
chpl_listing = chpl_home+'/spec/chapel_listing.tex'

print 'filename is : '+filename
print 'latexfile is: '+latexfile
print 'chpl_listing: '+chpl_listing

fh = open(latexfile, 'w')
fh.write('\\documentclass[11pt]{article}\n')
fh.write('\\usepackage{times}\n')
fh.write('\\usepackage{fullpage}\n')
fh.write('\\usepackage{listings}\n')
fh.write('\\input{'+chpl_listing+'}\n')
fh.write('\\lstset{stepnumber=1, mathescape=false}\n')
fh.write('\\begin{document}\n')
fh.write('\\lstinputlisting{'+realfile+'}')
fh.write('\\end{document}\n')
fh.close()

os.chdir(tmpdir)
os.system('pdflatex '+latexfile)
os.system('cp '+filename+'.pdf '+cwd)
os.chdir(cwd)

shutil.rmtree(tmpdir)
