]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi32.py
release: 1.0.3
[lilypond.git] / scripts / ly2dvi32.py
1 #!@PYTHON@
2
3 name = 'ly2dvi'
4 version = '0.0.1'
5
6 import sys
7 import os
8 import getopt
9 import re
10 import string
11 import time
12 import glob
13
14 class Input:
15
16     def __init__(this):
17        this.__fd = None 
18
19     def open(this,file):
20         for i in [''] + Props.get('include')[0:]:
21             ifile = os.path.join(i,file)
22             for j in ['','.ly','.fly']:
23                 jfile = ifile+j
24                 try:
25                     this.__fd = open( jfile, 'r' )
26                     return
27                 except:
28                     pass
29         sys.exit('ExitNotFound', file)
30
31     def close(this):
32         this.__fd.close()
33
34     def type(this):
35         firstline = this.__fd.readline()
36         this.__fd.seek(0)
37         if  re.match('% Creator: GNU LilyPond [0-9]+[.0-9]+',firstline ):
38             return 'output'
39         else:
40             return 'source'
41 #
42 # Scan file for variable settings
43 #
44     def setVars(this):  
45         """Scan source file for variable settings"""
46         varTable = [
47             #   regexp              set method
48             #   ------              ----------
49             ( 'language',        Props.setLanguage ),
50             ( 'latexheaders',    Props.setHeader ),
51             ( 'orientation',     Props.setOrientation ),
52             ( 'paperpapersize',  Props.setPaperZize ),
53             ( 'papertextheight', Props.setTextHeight ),
54             ( 'paperlinewidth',  Props.setLineWidth ),
55             ( 'filename',        Props.setFilename ),
56             ]
57
58         titles={}
59         line='prime the pump' # ugh
60         while line:
61             line=this.__fd.readline()
62             m=re.match('\\\\def\\\\mudela([\w]+){(.*)}',line)
63             if m:
64                 for var in varTable:
65                     if m.group(1) == var[0]:
66                         var[1](m.group(2),'file')
67                         break
68                 for var in Props.get('titledefs'):
69                     if m.group(1) == var:
70                         titles[var]=m.group(2)
71                         break
72         Props.setTitles(titles,'file')
73         this.__fd.seek(0)
74
75 class TeXOutput:
76
77     def __init__(this):
78        this.__fd = None 
79        this.__base = ''
80        this.__outfile = ''
81
82     def write(this,str):
83         this.__fd.write(str)
84
85     def start(this,file):
86         """Start the latex file"""
87         now=time.asctime(time.localtime(time.time()))
88         linewidth = Props.get('linewidth')
89         textheight = Props.get('textheight')
90
91         if Props.get('orientation') == 'landscape':
92             pagewidth = Props.get('pageheight')
93             pageheight = Props.get('pagewidth')
94         else:
95             pageheight = Props.get('pageheight')
96             pagewidth = Props.get('pagewidth')
97                              
98         horizontalMarginArg =  ( (pagewidth - linewidth)/2 )   
99         verticalMarginArg =  ( (pageheight - textheight)/2  )
100
101         top="""\
102 %% Creator: %s
103 %% Automatically generated from  %s, %s
104
105 \\documentclass[%s]{article}
106
107 %s 
108 \\usepackage{geometry}
109 \\usepackage[latin1]{inputenc} 
110 %%\\usepackage[T1]{fontenc} 
111 %s 
112 %%\\addtolength{\\oddsidemargin}{-1cm} 
113 %%\\addtolength{\\topmargin}{-1cm} 
114 %%\\setlength{\\textwidth}{%s} 
115 %%\\setlength{\\textheight}{%s} 
116 \\geometry{width=%spt, left=%spt, height=%spt, top=%spt} 
117 \\input lilyponddefs 
118 \\input titledefs 
119 %s 
120 \\begin{document}
121 """ % ( program_id(), Props.get('filename'), now, Props.get('papersize'),
122         Props.get('language'), Props.get('pagenumber'), linewidth, textheight,
123         linewidth, horizontalMarginArg, textheight, verticalMarginArg,
124         Props.get('header') )
125         
126         pathcomp = os.path.splitext(file)
127         this.__base = pathcomp[0]
128         this.__outfile = '%s.%d%s' % (pathcomp[0], os.getpid(), pathcomp[1])
129         try:
130             this.__fd = open(this.__outfile,"w")
131         except:
132             sys.exit('ExitNoWrite', this.__outfile)
133         this.write(top)
134         this.__mudelaDefs('')
135         this.write("""\
136 \\cmrtwenty% ugh
137 \\makelilytitle
138 """) 
139
140     def next(this):
141         this.write("""\
142 \\def\\theopus{}%
143 \\def\\thepiece{}%
144 \\def\\mudelaopus{}%
145 \\def\\mudelapiece{}%
146 """)
147         this.__mudelaDefs("\\def")
148         this.write("""\
149 \\def\\theopus{\\mudelaopus}% ugh
150 \\def\\thepiece{\\mudelapiece}%
151 \\makelilypiecetitle
152 """)
153
154     def __mudelaDefs(this,opt):
155         titles = Props.get('titles')
156         for key in titles.keys():
157             this.write('%s\\mudela%s{%s}%%\n' % (opt,key,titles[key]))
158
159     def end(this):
160         outfile=this.__base + '.dvi'
161         if Props.get('output') != '':
162             outfile = os.path.join(Props.get('output'), outfile )
163             
164         this.write("""\
165 \\vfill\\hfill{\\LilyIdString}
166 \\end{document}
167 """)
168         this.__fd.close()
169         stat = os.system('latex \'\\nonstopmode \\input %s\'' %
170                          (this.__outfile))
171         if stat:
172             sys.exit('ExitBadLatex')
173         if os.path.isfile(outfile):
174             os.remove(outfile)
175         os.rename(this.__base + '.' + str(os.getpid()) + '.dvi', outfile)
176
177 class Properties:
178
179     def __set(this,var,value,requester):
180         if this.__overrideTable[requester] < this.__data[var][1]:
181             return 0
182         else:
183             this.__data[var] = [value, this.__overrideTable[requester]]
184
185     def get(this,var):
186         if var == 'include' or var == 'lilyOutputFiles':
187             return this.__data[var][0][0:]  # return a copy not a ref
188         else:
189             return this.__data[var][0]
190
191     def get_texfile_path (this, var):
192             path =''
193             cmd =('kpsewhich tex %s' % var)
194             pipe = os.popen (cmd, 'r')
195             path = pipe.readline ()[:-1] # chop off \n
196             if not path:
197                     path = os.path.join(this.get('root'), 'texmf', 'tex', 'lilypond', var)
198
199             fd = open(path, 'r')
200             return fd
201
202     def __init__(this):
203         this.__overrideTable = {
204             'init'        : 0,
205             'environment' : 1,
206             'rcfile'      : 2,
207             'file'        : 3,
208             'commandline' : 4,
209             'program'     : 5
210             }
211
212         this.__roverrideTable = {} # reverse lookup
213         for i in this.__overrideTable.items():
214             this.__roverrideTable[i[1]]=i[0]
215         
216         this.__data = {
217             'pagewidth'    :  [597, this.__overrideTable['init']],
218             'pageheight'   :  [845, this.__overrideTable['init']],
219             'papersize'    :  ['a4paper', this.__overrideTable['init']],
220             'textheight'   :  [0, this.__overrideTable['init']],
221             'linewidth'    :  [0, this.__overrideTable['init']],
222             'orientation'  :  ['portrait', this.__overrideTable['init']],
223             'language'     :  ['%', this.__overrideTable['init']],
224             'include'      :  [[], this.__overrideTable['init']],
225             'debug'        :  [0, this.__overrideTable['init']],
226             'keeplilypond' :  [0, this.__overrideTable['init']],
227             'keeply2dvi'   :  [0, this.__overrideTable['init']],
228             'pagenumber'   :  ['%', this.__overrideTable['init']],
229             'separate'     :  [0, this.__overrideTable['init']],
230             'output'       :  ['', this.__overrideTable['init']],
231             'header'       :  ['%', this.__overrideTable['init']],
232             'dependencies' :  [0, this.__overrideTable['init']],
233             'root'         :  ['', this.__overrideTable['init']],
234             'tmp'          :  ['d:\tmp', this.__overrideTable['init']],
235             'filename'     :  ['', this.__overrideTable['init']],
236             'titledefs'    :  [[], this.__overrideTable['init']],
237             'titles'       :  [{}, this.__overrideTable['init']],
238             'lilyOutputFiles' :  [[], this.__overrideTable['init']],
239             }
240
241         if os.environ.has_key('LILYINCLUDE'):
242             tmp=this.get('include')
243             for s in string.split(os.environ['LILYINCLUDE'],os.pathsep):
244                 tmp.append(s)
245             this.__set('include', tmp, 'environment')    
246
247         if os.environ.has_key('LILYPOND'):
248             this.__set('root',os.environ['LILYPOND'], 'environment')
249         else:
250             p=os.path.split(sys.argv[0])
251             p=os.path.split(p[0])
252             this.__set('root',p[0],'init')
253
254         if os.environ.has_key ('TEXINPUTS'):
255                 t = os.pathsep + os.environ['TEXINPUTS']
256         os.environ['TEXINPUTS'] = os.path.join(this.get('root'), 'texmf',
257                                                'tex', 'lilypond' ) + t
258
259         if os.environ.has_key('TMP'):
260             this.__set('tmp',os.environ['TMP'],'environment')
261
262         if not os.environ.has_key('HOME'):
263             if os.environ.has_key('HOMEDRIVE') and \
264                  os.environ.has_key('HOMEPATH'):
265                 os.environ['HOME'] = os.environ['HOMEDRIVE'] + \
266                                      os.environ['HOMEPATH']
267             else:
268                 os.environ['HOME'] = os.curdir
269         
270
271         fd =this.get_texfile_path ('titledefs.tex')
272         mudefs=[]    
273         line='prime the pump' # ugh
274         while line:
275             line=fd.readline()
276             m=re.match('\\\\newcommand\*{\\\\mudela([\w]+)}',line)
277             if m:
278                 mudefs.append(m.group(1))
279         fd.close
280         this.__set('titledefs', mudefs, 'init')
281
282 #
283 # Read rc file
284 #
285     def rcfile(this):
286         """Read RCfile"""
287         varTable = [
288             #   name              set method
289             #   ----              ----------
290             ( 'LILYPOND',       this.setInclude ),
291             ( 'LANGUAGE',       this.setLanguage ),
292             ( 'LATEXHF',        this.setHeader ),
293             ( 'ORIENTATION',    this.setOrientation ),
294             ( 'OUTPUTDIR',      this.setOutput ),
295             ( 'PAPERSIZE',      this.setPaperZize ),
296             ( 'PHEIGHT',        this.setTextHeight ),
297             ( 'TMP',            this.setTmp ),
298             ( 'PWIDTH',         this.setLineWidth ),
299             ]
300
301         for d in [os.path.join(this.get('root'),'share','lilypond'), \
302                   os.environ['HOME'], os.curdir ]:
303             file=os.path.join(d,'.lilyrc')
304             try:
305                 fd = open( file, 'r' )
306             except:
307                 continue
308             
309             line='prime the pump' # ugh
310             while line:
311                 line=fd.readline()
312                 if re.match('#.*',line):
313                     continue
314                 m=re.search('([\w]+)=(.*)',line)
315                 if m:
316                     for var in varTable:
317                         if m.group(1) == var[0]:
318                             var[1](m.group(2),'rcfile')
319                             break
320             fd.close
321
322 #
323 # Set paper size
324 #
325     def setPaperZize(this,size,requester):
326         paperTable = [
327             # regex          width    height      name
328             # -----          -----    ------      ----
329             ( 'a0.*',        2389,    3381,    'a0paper' ),
330             ( 'a1$|a1p.*',   1690,    2389,    'a1paper' ),
331             ( 'a2.*',        1194,    1690,    'a2paper' ),
332             ( 'a3.*',        845,     1194,    'a3paper' ),
333             ( 'a4.*',        597,     845,     'a4paper' ),
334             ( 'a5.*',        423,     597,     'a5paper' ),
335             ( 'a6.*',        298,     423,     'a6paper' ),
336             ( 'a7.*',        211,     298,     'a7paper' ),
337             ( 'a8.*',        305,     211,     'a8paper' ),
338             ( 'a9.*',        105,     305,     'a9paper' ),
339             ( 'a10.*',       74,      105,     'a10paper' ),
340             ( 'b0.*',        2847,    4023,    'b0paper' ),
341             ( 'b1.*',        2012,    2847,    'b1paper' ),
342             ( 'b2.*',        1423,    2012,    'b2paper' ),
343             ( 'b3.*',        1006,    1423,    'b3paper' ),
344             ( 'b4.*',        712,     1006,    'b4paper' ),
345             ( 'b5.*',        503,     712,     'b5paper' ),
346             ( 'archA$',      650,     867,     'archApaper' ),
347             ( 'archB$',      867,     1301,    'archBpaper' ),
348             ( 'archC$',      1301,    1734,    'archCpaper' ),
349             ( 'archD$',      1734,    2602,    'archDpaper' ),
350             ( 'archE$',      2602,    3469,    'archEpaper' ),
351             ( 'flsa$|flse$', 614,     940,     'flsapaper' ),
352             ( 'halfletter$', 397,     614,     'halfletterpaper' ),
353             ( 'ledger$',     1229,    795,     'ledgerpaper' ),
354             ( 'legal$',      614,     1012,    'legalpaper' ),
355             ( 'letter$',     614,     795,     'letterpaper' ),
356             ( 'note$',       542,     723,     'notepaper' )
357             ]
358
359         found=0
360         for paper in paperTable:
361             if re.match(paper[0],size):
362                 found=1
363                 this.__set('pagewidth',paper[1],requester)
364                 this.__set('pageheight',paper[2],requester)
365                 this.__set('papersize',paper[3],requester)
366                 break
367
368         if not found:
369             sys.exit('ExitBadPaper',size)
370
371 #
372 # set Text Height
373 #
374     def setTextHeight(this,size,requester):
375         m=re.match('([0-9][.0-9]*)(cm|mm|pt|$)',size)
376         if m:
377             if m.group(2) == 'cm':
378                 this.__set('textheight',\
379                            float(m.group(1)) * 72.27/2.54, requester )
380             elif m.group(2) == 'mm':
381                 this.__set('textheight',\
382                            float(m.group(1)) * 72.27/25.4, requester )
383             elif m.group(2) == 'pt':
384                 this.__set('textheight', float(m.group(1)), requester )
385             elif m.group(2) == '':
386                 this.__set('textheight', float(m.group(1)), requester )
387             else:
388                 sys.exit('ExitBadHeight', m.group(2))
389         else:           
390             sys.exit('ExitBadHeight', size)
391 #
392 # set Text Width
393 #
394     def setLineWidth(this,size,requester):
395         m=re.match('([0-9][.0-9]*)(cm|mm|pt|$)',size)
396         if m:
397             if m.group(2) == 'cm':
398                 this.__set('linewidth', \
399                 float(m.group(1)) * 72.27/2.54, requester )
400             elif m.group(2) == 'mm':
401                 this.__set('linewidth', \
402                 float(m.group(1)) * 72.27/25.4, requester )
403             elif m.group(2) == 'pt':
404                 this.__set('linewidth', float(m.group(1)), requester )
405             elif m.group(2) == '':
406                 this.__set('linewidth', float(m.group(1)), requester )
407             else:
408                 sys.exit('ExitBadWidth', m.group(2))
409         else:           
410             sys.exit('ExitBadWidth', size)
411 #
412 # Set Orientation
413 #
414     def setOrientation(this,orient,requester):
415         if orient == 'landscape' or orient == 'portrait':
416             this.__set('orientation', orient, requester )
417         else:
418             sys.exit('ExitBadOrient', orient)
419 #
420 # Set Language
421 #
422     def setLanguage(this,lang,requester):
423         this.__set('language', '\\usepackage[%s]{babel}' % (lang), requester )
424 #
425 # Append Include
426 #
427     def setInclude(this,inc, requester):
428         tmp = this.get('include')
429         tmp.append(inc)
430         this.__set('include', tmp, requester )
431 #
432 # Set debug flag
433 #
434     def setDebug(this,requester):
435         this.__set('debug',1,requester)
436
437 #
438 # Clear debug flag
439 #
440     def clearDebug(this, requester):
441         this.__set('debug',0,requester)
442 #
443 # Set Keeplilypond flag
444 #
445     def setKeeplilypond(this, requester):       
446         this.__set('keeplilypond',1,requester)
447
448 #
449 # Clear Keeplilypond flag
450 #
451     def clearKeeplilypond(this, requester):     
452         this.__set('keeplilypond',0,requester)
453
454 #
455 # Set Keeply2dvi flag
456 #
457     def setKeeply2dvi(this, requester): 
458         this.__set('keeply2dvi',1,requester)
459 #
460 # Clear Keeply2dvi flag
461 #
462     def clearKeeply2dvi(this, requester):       
463         this.__set('keeply2dvi',0,requester)
464 #
465 # Set No page number flag
466 #
467     def setNonumber(this, requester):   
468         this.__set('pagenumber','\\pagestyle{empty}',requester)
469
470 #
471 # Clear No page number flag
472 #
473     def clearNonumber(this, requester): 
474         this.__set('pagenumber','%',requester)
475 #
476 # Set separate flag
477 #
478     def setSeparate(this, requester):   
479         this.__set('separate',1,requester)
480
481 #
482 # Clear separate flag
483 #
484     def clearSeparate(this, requester): 
485         this.__set('separate',0,requester)
486
487 #
488 # Set output directory name
489 #
490     def setOutput(this,out,requester):
491         this.__set('output',out,requester)
492
493 #
494 # Set latex header name
495 #
496     def setHeader(this,head, requester):
497         this.__set('header',head,requester)
498 #
499 # Set Dependencies flag to generate makefile dependencies
500 #
501     def setDependencies(this, requester):       
502         this.__set('dependencies',1,requester)
503
504 #
505 # Clear Dependencies flag
506 #
507     def clearDependencies(this, requester):     
508         this.__set('dependencies',0,requester)
509 #
510 # Set tmp directory
511 #
512     def setTmp(this,dir, requester):    
513         this.__set('tmp',dir,requester)
514 #
515 # Set mudela source file name
516 #
517     def setFilename(this,file, requester):      
518         this.__set('filename',file,requester)
519 #
520 # Set title commands
521 #
522     def setTitles(this,titles, requester):      
523         this.__set('titles',titles,requester)
524
525     def addLilyOutputFiles(this,file,requester):
526         tmp = this.get('lilyOutputFiles')
527         tmp.append(file)
528         this.__set('lilyOutputFiles',tmp,requester)
529
530     def printProps(this):
531         for key in this.__data.keys():
532             print "%s <%s>:<%s>" % (key,this.get(key),
533                                     this.__roverrideTable[this.__data[key][1]])
534
535 def getLilyopts():
536     inc = ''    
537     if len(Props.get('include')) > 0: 
538         inc = '-I ' + string.join(Props.get('include'),os.pathsep)
539     else:
540
541         if Props.get('dependencies'):
542             dep=' -d'
543         else:
544             dep=''
545         return inc + dep
546     return inc
547
548 def writeLilylog(contents):
549     if Props.get('keeplilypond'):
550         file='lilylog.' + str(os.getpid())
551         output = Props.get('output')
552         if output != '':
553             file = os.path.join( output, file )
554         try:
555             fd = open( file, 'w' )
556         except:
557             sys.exit('ExitNoWrite', file)
558         fd.write(contents)
559         fd.close()
560
561 def getTeXFile(contents):
562     m = re.search('^TeX output to (.+)\.tex', contents,re.M)
563     if m:
564         return ( m.group(1)+'.tex' )
565     else:
566         sys.exit('ExitNoTeXName')
567
568 def program_id ():
569     return name + ' ' + version;
570
571
572 def mailaddress():
573     try:
574         return os.environ['MAILADDRESS']
575     except KeyError:
576         return '(address unknown)'
577
578
579 def identify ():
580     sys.stderr.write (program_id () + '\n')
581
582 def help ():
583     sys.stderr.write (
584         'Generate dvi file from mudela or lilypond output\n'
585         'Usage: ' + name + ' [OPTION]... [FILE]...\n'
586         '\n'
587         'Options:\n'
588         '  -D,--debug           increase verbosity\n'
589         '  -F,--headers=        name of additional LaTeX headers file\n'
590         '  -H,--Height=         set paper height (points) (see manual page)\n'
591         '  -I,--include=DIR     add DIR to LilyPond\'s search path\n'
592         '  -K,--keeplilypond    keep lilypond output files\n'
593         '  -L,--landscape       set landscape orientation\n'
594         '  -N,--nonumber        switch off page numbering\n'
595         '  -O,--orientation=    set orientation (obsolete - use -L instead)\n'
596         '  -W,--Width=          set paper width (points) (see manual page)\n'
597         '  -d,--dependencies    tell lilypond make a dependencies file\n'
598         '  -h,--help            this help text\n'
599         '  -k,--keeply2dvi      keep ly2dvi output files\n'
600         '  -l,--language=       give LaTeX language (babel)\n'
601         '  -o,--output=         set output directory\n'
602         '  -p,--papersize=      give LaTeX papersize (eg. a4)\n'
603         '  -s,--separate        run all files separately through LaTeX\n'
604         '\n'
605         'files may be (a mix of) input to or output from lilypond(1)\n'
606         )
607
608
609 def main():
610     """Generate dvi files from lilypond source/output"""
611
612     infile = Input()
613     outfile = TeXOutput()
614     texInputFiles=[]
615
616     Props.rcfile()
617     (options, files) = getopt.getopt (sys.argv[1:],
618                                       'DF:H:I:KLNW:dhkl:o:p:s',
619                                       ['debug', 'headers=', 'Height=',
620                                        'include=', 'keeplilypond', 'landscape',
621                                        'nonumber', 'Width=', 'dependencies',
622                                        'help', 'keeply2dvi', 'language=',
623                                        'output=', 'papersize=', 'separate'])
624     for opt in options:
625         o = opt[0]
626         a = opt[1]
627         if o == '--debug' or o == '-D':
628             Props.setDebug('commandline')
629         elif o == '--headers' or o == '-F':
630             Props.setHeader(a,'commandline')
631         elif o == '--include' or o == '-I':
632             Props.setInclude(a,'commandline')
633         elif o == '--Height' or o == '-H':
634             Props.setTextHeight(a,'commandline')
635         elif o == '--keeplilypond' or o == '-K':
636             Props.setKeeplilypond('commandline')
637         elif o == '--landscape' or o == '-L':
638             Props.setOrientation('landscape','commandline')
639         elif o == '--nonumber' or o == '-N':
640             Props.setNonumber('commandline')
641         elif o == '--Width' or o == '-W':
642             Props.setLineWidth(a,'commandline')
643         elif o == '--dependencies' or o == '-d':
644             Props.setDependencies('commandline')
645         elif o == '--help' or o == '-h':
646             help()
647             return 0
648         elif o == '--keeply2dvi' or o == '-k':
649             Props.setKeeply2dvi('commandline')
650         elif o == '--language' or o == '-l':
651             Props.setLanguage(a,'commandline')
652         elif o == '--output' or o == '-o':
653             Props.setOutput(a,'commandline')
654         elif o == '--papersize' or o == '-p':
655             Props.setPaperZize(a,'commandline')
656         elif o == '--separate' or o == '-s':
657             Props.setSeparate('commandline')
658
659     if len(files):
660         for file in files:
661             infile.open(file)
662             type = infile.type()
663             infile.close()
664             if type == 'source':
665                 cmd = 'lilypond %s %s 2>&1' % (getLilyopts(), file)
666                 fd = os.popen( cmd , 'r' )
667                 log = fd.read()
668                 stat = fd.close()
669                 print log
670                 if stat:
671                     sys.exit('ExitBadLily', cmd )
672                 texFile=getTeXFile(log)
673                 writeLilylog(log)
674                 Props.addLilyOutputFiles(texFile,'program')
675                 texInputFiles.append(texFile)
676             else:
677                 texInputFiles.append(file)
678
679         firstfile=1
680         for file in texInputFiles:
681             infile.open(file)
682             infile.setVars() # first pass set variables
683             infile.close()
684             Props.printProps()
685             if firstfile:
686                 outfile.start(file)
687             else:
688                 outfile.next()
689             outfile.write("""\
690 \\input{%s}
691 """ % (file))
692             if Props.get('separate'):
693                 outfile.end()
694             else:
695                 firstfile=0
696         if not Props.get('separate'):
697             outfile.end()
698     else:
699         help()
700         sys.exit('ExitBadArgs','No files specified')
701
702 #
703 # Exit values
704 #
705 ExitTable = {
706     'ExitInterupt'         : ['Ouch!', 1 ],
707     'ExitBadArgs'          : ['Wrong number of arguments', 2 ],
708     'ExitNotFound'         : ['File not found', 3 ],
709     'ExitBadPaper'         : ['Unknown papersize', 4 ],
710     'ExitBadHeight'        : ['Invalid Height specification', 5 ],
711     'ExitBadWidth'         : ['Invalid Width specification', 6 ],
712     'ExitBadOrient'        : ['Invalid Orientation specification', 7 ],
713     'ExitNoWrite'          : ['Permission denied', 8 ],
714     'ExitNoTeXName'        : ['hmm, I could not find an output file name', 9 ],
715     'ExitBadLily'          : ['Lilypond failed', 10 ],
716     'ExitBadLatex'         : ['Latex failed', 11 ],
717     'ExitUnknown'          : ['Unknown Exit Code', 20 ],
718     }
719
720 def cleanup():
721     lilyfiles = []
722     tmpfiles = []
723     if not Props.get('keeplilypond'):
724         lilyfiles = Props.get('lilyOutputFiles')
725     if not Props.get('keeply2dvi'):
726         tmpfiles = glob.glob('*.' + str(os.getpid()) + '.*' )
727     for file in lilyfiles + tmpfiles:
728         if os.path.isfile(file):
729             os.remove(file)
730
731
732
733
734
735
736
737 identify()
738 Props = Properties()
739
740 try:
741     main()
742
743 except KeyboardInterrupt:
744     print ExitTable['ExitInterupt'][0]
745     cleanup()
746     sys.exit(ExitTable['ExitInterupt'][1])
747
748 except SystemExit, errno:
749     if ExitTable.has_key(errno.args[0]):
750         msg = ExitTable[errno.args[0]]
751     else:
752         msg = ExitTable['ExitUnknown']
753     if len(errno.args) > 1:  
754         sys.stderr.write( '%s: %s: %s\n' % (name, msg[0], errno.args[1]))
755     else:
756         sys.stderr.write( '%s %s\n' % (name, msg[0]))
757     cleanup()
758     sys.exit(msg[1])
759 else:
760     cleanup()
761
762     
763
764                                    
765
766
767