]> git.donarmstrong.com Git - lilypond.git/blob - scripts/mudela-book.py
patch::: 1.2.2.jcn2
[lilypond.git] / scripts / mudela-book.py
1 #!@PYTHON@
2
3 import os
4 import string
5 import re
6 import getopt
7 import sys
8 import __main__
9
10 outdir = 'out'
11 initfile = ''
12 program_version = '@TOPLEVEL_VERSION@'
13
14 cwd = os.getcwd ()
15 include_path = [cwd]
16
17 # TODO: use splitting iso. \mudelagraphic.
18
19 #
20 default_music_fontsize = 16
21 default_text_fontsize = 12
22
23 # latex linewidths:
24 # indices are no. of columns, papersize,  fontsize
25 # Why can't this be calculated?
26 latex_linewidths = {
27  1: {'a4':{10: 345, 11: 360, 12: 390},
28          'a5':{10: 276, 11: 276, 12: 276},
29          'b5':{10: 345, 11: 356, 12: 356},
30          'letter':{10: 345, 11: 360, 12: 390},
31          'legal': {10: 345, 11: 360, 12: 390},
32          'executive':{10: 345, 11: 360, 12: 379}},
33  2: {'a4':{10: 167, 11: 175, 12: 190},
34          'a5':{10: 133, 11: 133, 12: 133},
35          'b5':{10: 167, 11: 173, 12: 173},
36          'letter':{10: 167, 11: 175, 12: 190},
37          'legal':{10: 167, 11: 175, 12: 190},
38          'executive':{10: 167, 11: 175, 12: 184}}}
39
40
41 options = [
42   ('DIM',  '', 'default-mudela-fontsize', 'default fontsize for music.  DIM is assumed to in points'),
43   ('EXT', 'f', 'format', 'set format.  EXT is one of texi and latex.'),
44   ('', 'h', 'help', 'print help'),
45   ('DIR', 'I', 'include', 'include path'),
46   ('', '', 'init', 'mudela-book initfile'),
47 #  ('DIM', '', 'force-mudela-fontsize', 'force fontsize for all inline mudela. DIM is assumed to in points'),
48   ('', '', 'force-verbatim', 'make all mudela verbatim'),
49   ('', 'M', 'dependencies', 'write dependencies'),
50   ('', 'n', 'no-lily', 'don\'t run lilypond'),
51   ('FILE', 'o', 'outname', 'prefix for filenames'),
52   ('', 'v', 'version', 'print version information' )
53   ]
54
55 format = ''
56 no_lily = 0
57 no_match = 'a\ba'
58
59 # format specific strings, ie. regex-es for input, and % strings for output
60 output_dict= {
61         'latex': {
62                 'output-mudela-fragment' : r"""\begin[eps,fragment%s]{mudela}
63   \context Staff <
64     \context Voice{
65       %s
66     }
67   >
68 \end{mudela}""", 
69                 'output-mudela':r"""\begin%s{mudela}
70 %s
71 \end{mudela}""",
72                 'output-verbatim': r"""\begin{verbatim}%s\end{verbatim}""",
73                 'output-default-post': r"""\def\postMudelaExample{}""",
74                 'output-default-pre': r"""\def\preMudelaExample{}""",
75                 'output-eps': '\\noindent\\parbox{\\mudelaepswidth{%s.eps}}{\includegraphics{%s.eps}}',
76                 'output-tex': '\\preMudelaExample \\input %s.tex \\postMudelaExample\n'
77                 },
78         'texi' : {'output-mudela': """@mudela[%s]
79 %s
80 @end mudela
81 """,
82                   'output-verbatim': r"""@example
83 %s
84 @end example
85 """,
86                   'output-all': r"""@tex
87 \input %s.tex
88 @end tex
89 @html
90 <img src=%s.png>
91 @end html
92 """,
93                 }
94         }
95
96 re_dict = {
97         'latex': {'input': '\\\\input{?([^}\t \n}]*)',
98                   'include': '\\\\include{([^}]+)}',
99                  
100                   'comma-sep' : ', *',
101                   'header': r"""\\documentclass(\[.*?\])?""",
102                   'preamble-end': '\\\\begin{document}',
103                   'verbatim': r"""(?s)\\begin{verbatim}(.*?)\\end{verbatim}""",
104                   'verb': r"""\\verb(.)(.*?)\1""",
105                   'mudela-file': '\\\\mudelafile(\[[^\\]]+\])?{([^}]+)}',
106                   'mudela' : '\\\\mudela(\[.*?\])?{(.*?)}',
107                   'mudela-block': r"""(?s)\\begin(\[.*?\])?{mudela}(.*?)\\end{mudela}""",
108                   'interesting-cs': '\\\\(chapter|section|twocolumn|onecolumn)',
109                   'def-post-re': r"""\\def\\postMudelaExample""",
110                   'def-pre-re': r"""\\def\\preMudelaExample""",           
111                   },
112         'texi': {'input': '@include[ \n\t]+([^\t \n]*)',
113                  'include': no_match,
114                  'header': no_match,
115                  'preamble-end': no_match,
116                  'verbatim': r"""(?s)@example(.*?)@end example$""",
117                  'verb': r"""@code{(.*?)}""",
118                  'mudela-file': '@mudelafile(\[[^\\]]+\])?{([^}]+)}',
119                  'mudela' : '@mudela(\[.*?\])?{(.*?)}',
120                  'mudela-block': r"""(?s)@mudela(\[.*?\])?(.*?)@end mudela""",
121                  'interesting-cs': r"""[\\@](node|mudelagraphic)""",
122                   'comma-sep' : ', *',           
123                  }
124         }
125
126
127 for r in re_dict.keys ():
128         olddict = re_dict[r]
129         newdict = {}
130         for k in olddict.keys ():
131                 newdict[k] = re.compile (olddict[k])
132         re_dict[r] = newdict
133
134         
135 def get_output (name):
136         return  output_dict[format][name]
137
138 def get_re (name):
139         return  re_dict[format][name]
140
141
142 def bounding_box_dimensions(fname):
143         try:
144                 fd = open(fname)
145         except IOError:
146                 error ("Error opening `%s'" % fname)
147         str = fd.read (-1)
148         s = re.search('%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)', str)
149         if s:
150                 return (int(s.group(3))-int(s.group(1)), 
151                         int(s.group(4))-int(s.group(2)))
152         else:
153                 return (0,0)
154
155
156 def find_file (name):
157         for a in include_path:
158                 try:
159                         nm = os.path.join (a, name)
160                         f = open (nm)
161                         return nm
162                 except IOError:
163                         pass
164         return ''
165
166 def error (str):
167         sys.stderr.write (str + "\n  Exiting ... \n\n")
168         raise 'Exiting.'
169
170
171 def compose_full_body (body, opts):
172         "Construct the text of an input file: add stuff to BODY using OPTS as options."
173         paper = 'a4'
174         music_size = default_music_fontsize
175         latex_size = default_text_fontsize
176
177         cols = 1
178         for o in opts:
179                 m = re.search ('^(.*)paper$', o)
180                 if m:
181                         paper = m.group (1)
182                 
183
184                 m = re.match ('([0-9]+)pt', o)
185                 if m:
186                         music_size = string.atoi(m.group (1))
187
188                 m = re.match ('latexfontsize=([0-9]+)pt', o)
189                 if m:
190                         latex_size = string.atoi (m.group (1))
191
192
193         if 'twocolumn' in opts:
194                 cols = 2
195                 
196         if 'fragment' or 'singleline' in opts:
197                 l = -1.0;
198         else:
199                 l = latex_linewidths[cols][paper][latex_size]
200
201         # urg: breaks on \include of full score
202         # if not 'nofly' in opts and not re.search ('\\\\score', body):
203         #       opts.append ('fly')
204
205         if 'fly' in opts:
206                 body = r"""\score { 
207   \notes\relative c {
208     %s
209   }
210   \paper { }  
211 }""" % body
212
213                 
214         body = r"""
215 %% Generated by mudela-book.py
216 \include "paper%d.ly"
217 \paper  { linewidth = %f \pt; } 
218 """ % (music_size, l) + body
219
220         return body
221
222 def inclusion_func (match, surround):
223         insert = match.group (0)
224         try:
225                 (insert, d) = read_doc_file (match.group(1))
226                 deps = deps + d
227                 insert = surround + insert + surround
228         except:
229                 sys.stderr.write("warning: can't find %s, let's hope latex will\n" % m.group(1))
230
231         return (insert, deps)
232
233 def find_inclusion_chunks (regex, surround, str):
234         chunks = []
235         while str:
236                 m = regex.search (str)
237
238                 if m == None:
239                         chunks.append (('input', str))
240                         str = ''
241                         break
242
243                 chunks.append (('input', str[: m.start (0)]))
244                 chunks.append (('input', surround))
245                 chunks = chunks + read_doc_file (m.group (1))
246                 chunks.append (('input', surround))
247
248                 str = str [m.end (0):]
249         return chunks
250
251 def find_include_chunks (str):
252         return find_inclusion_chunks (get_re ('include'), '\\newpage', str)
253
254 def find_input_chunks (str):
255         return find_inclusion_chunks (get_re ('input'), '', str)        
256
257 def read_doc_file (filename):
258         """Read the input file, substituting for \input, \include, \mudela{} and \mudelafile"""
259         str = ''
260         for fn in [filename, filename+'.tex', filename+'.doc']:
261                 try:
262                         f = open(fn)
263                         str = f.read (-1)
264                 except:
265                         pass
266                 
267
268         if not str:
269                 raise IOError
270
271         retdeps =  [filename]
272
273         if __main__.format == '':
274                 latex =  re.search ('\\\\document', str[:200])
275                 texinfo =  re.search ('@node', str[:200])
276                 if (texinfo and latex) or not (texinfo or latex):
277                         error("error: can't determine format, please specify")
278                 if texinfo:
279                         __main__.format = 'texi'
280                 else:
281                         __main__.format = 'latex'
282                         
283         chunks = find_verbatim_chunks (str)
284         newchunks = []
285
286         for func in (find_include_chunks, find_input_chunks):
287                 for c in chunks:
288                         if c[0] == 'input':
289                                 ch = func (c[1])
290                                 newchunks = newchunks + ch
291                         else:
292                                 newchunks.append (c)
293
294         
295         return chunks
296
297
298
299 def scan_preamble (str):
300         options = []
301         m = get_re ('header').search( str)
302
303         # should extract paper & fontsz.
304         if m and m.group (1):
305                 options = options + re.split (',[\n \t]*', m.group(1)[1:-1])
306
307         def verbose_fontsize ( x):
308                 # o ??
309                 #if o.match('[0-9]+pt'):
310                 if re.match('[0-9]+pt', x):
311                         return 'latexfontsize=' + x
312                 else:
313                         return x 
314                         
315         options = map (verbose_fontsize, options)
316
317         return options
318
319
320 def completize_preamble (str):
321         m = get_re ('preamble-end').search( str)
322         if not m:
323                 return str
324         
325         preamble = str [:m.start (0)]
326         str = str [m.start(0):]
327         
328         if not get_re('def-post-re').search (preamble):
329                 preamble = preamble + get_output('output-default-post')
330         if not get_re ('def-pre-re').search(  preamble):
331                 preamble = preamble + get_output ('output-default-pre')
332
333         # UGH ! BUG!
334         #if  re.search ('\\\\includegraphics', str) and not re.search ('usepackage{graphics}',str):
335
336         preamble = preamble + '\\usepackage{graphics}\n'
337
338         return preamble + str
339
340 def find_verbatim_chunks (str):
341         """Chop STR into a list of tagged chunks, ie. tuples of form
342         (TYPE_STR, CONTENT_STR), where TYPE_STR is one of 'input' and 'verbatim'
343         """
344
345         
346         chunks = []
347         
348         while str:
349                 m = get_re ('verbatim').search( str)
350                 m2 = get_re ("verb").search( str)
351
352                 if  m == None and m2 == None:
353                         chunks.append (('input', str))
354                         str = ''
355                         break
356
357                 if m == None:
358                         m = m2
359
360                 if m2 and m2.start (0) < m.start (0):
361                         m = m2
362                         
363                 chunks.append (('input', str[:m.start (0)]))
364                 chunks.append (('verbatim', m.group (0)))
365                 
366                 str = str [m.end(0):]
367         return chunks         
368
369
370 def find_mudela_shorthand_chunks (str):
371         return [('input', find_mudela_shorthands(str))]
372         
373 def find_mudela_shorthands (b):
374         def mudela_short (match):
375                 "Find \mudela{}, and substitute appropriate \begin / \end blocks."
376                 opts = match.group (1)
377                 if opts:
378                         opts = ',' + opts[1:-1]
379                 else:
380                         opts = ''
381                 return get_output ('output-mudela-fragment')  % (opts, match.group (2))
382
383         def mudela_file (match):
384                 "Find \mudelafile, and substitute appropriate \begin / \end blocks."
385                 d = [] #, d = retdeps
386                 full_path = find_file (match.group (2))
387                 if not full_path:
388                         error("error: can't find file `%s'\n" % match.group(2))
389
390                 d.append (full_path)
391                 f = open (full_path)
392                 str = f.read (-1)
393                 opts = match.group (1)
394                 if opts:
395                         opts = re.split (',[ \n\t]*', opts[1:-1])
396                 else:
397                         opts = []
398
399                 if re.search ('.fly$', full_path):
400                         opts.append ('fly')
401                 elif re.search ('.sly$', full_path):
402                         opts = opts + [ 'fly','fragment']
403                 elif re.search ('.ly$', full_path):
404                         opts .append ('nofly')
405                         
406                 str_opts = string.join (opts, ',')
407                 if str_opts: str_opts = '[' + str_opts + ']'
408
409
410                 str = "%% copied from %s" % full_path + str 
411                 return get_output ('output-mudela') % (str_opts, str)
412
413         b = get_re('mudela-file').sub (mudela_file, b)
414         b = get_re('mudela').sub (mudela_short, b)
415         return b
416         
417 def find_mudela_chunks (str):
418         """Find mudela blocks, while watching for verbatim. Returns
419         (STR,MUDS) with \mudelagraphic substituted for the blocks in STR,
420         and the blocks themselves MUDS"""
421
422         chunks = []
423         while str:
424                 m = get_re ("mudela-block").search( str)
425                 if not m:
426                         chunks.append (('input', str))
427                         str = ''
428                         break
429
430                 chunks.append (('input', str[:m.start (0)]))
431                 
432                 opts = m.group (1)
433                 if opts:
434                         opts = opts[1:-1]
435                 else:
436                         opts = ''
437                 optlist = get_re('comma-sep').split (opts)
438                 
439                 body = m.group (2)
440                 chunks.append (('mudela', body, optlist))
441
442                 str = str [m.end (0):]
443
444         return chunks
445
446
447
448 def advance_counters (counter, opts, str):
449         """Advance chap/sect counters,
450         revise OPTS. Return the new counter tuple"""
451         
452         (chapter, section, count) = counter
453         done = ''
454         while str:
455                 m = get_re ('interesting-cs').search(str)
456                 if not m:
457                         done = done + str
458                         str = ''
459                         break
460                 
461                 done = done + str[:m.end (0)]
462                 str = str[m.end(0):]
463                 g = m.group (1)
464
465                 if g == 'twocolumn':
466                         opts.append ('twocolumn')
467                 elif g  == 'onecolumn':
468                         try:
469                                 current_opts.remove ('twocolumn')
470                         except IndexError:
471                                 pass
472                 elif g == 'chapter':
473                         (chapter, section, count)  = (chapter + 1, 0, 0)
474                 elif g == 'section' or g == 'node':
475                         (section, count)  = (section + 1, 0)
476                         
477
478         return (chapter, section, count)
479
480
481 def schedule_mudela_block (base, chunk, extra_opts):
482
483         """Take the body and options from CHUNK, figure out how the
484         real .ly should look, and what should be left MAIN_STR (meant
485         for the main file).  The .ly is written, and scheduled in
486         TODO.
487
488         Return: a chunk (TYPE_STR, MAIN_STR, OPTIONS, TODO)
489
490         TODO has format [basename, extension, extension, ... ]
491         
492         """
493
494         (type, body, opts) = chunk
495         assert type == 'mudela'
496         opts = opts +  extra_opts
497         
498         newbody = ''
499         if 'verbatim' in opts:
500                 verbatim_mangle = body
501                 if __main__.format == 'texi':
502                         verbatim_mangle = re.sub ('([{}])', '@\\1', body)
503                 newbody = get_output ('output-verbatim') % verbatim_mangle
504
505         file_body = compose_full_body (body, opts)
506         updated = update_file (file_body, base + '.ly')
507
508         todo = [base]                   # UGH.
509         
510         if not os.path.isfile (base + '.tex') or updated:
511                 todo.append ('tex')
512                 updated = 1
513
514         for o in opts:
515                 m = re.search ('intertext="(.*?)"', o)
516                 if m:
517                         newbody = newbody  + m.group (1)
518
519         if format == 'texi':
520                 opts.append ('png')
521
522         if 'png' in opts:
523                 opts.append ('eps')
524
525         if 'eps' in opts and ('tex' in todo or
526                               not os.path.isfile (base + '.eps')):
527                 todo.append ('eps')
528
529         if 'png' in opts and ('eps' in todo or
530                               not os.path.isfile (base + '.png')):
531                 todo.append ('png')
532
533         if format == 'latex':
534                 if 'eps' in opts :
535                         newbody = newbody + get_output ('output-eps') %  (base, base)
536                 else:
537                         newbody = newbody + get_output ('output-tex') % base
538
539         elif format == 'texi':
540                 newbody = newbody + get_output ('output-all') % (base, base) 
541
542
543         
544         return ('mudela', newbody, opts, todo)
545
546 def find_eps_dims (match):
547         "Fill in dimensions of EPS files."
548         fn =match.group (1)
549         dims = bounding_box_dimensions (fn)
550
551         return '%ipt' % dims[0]
552
553
554 def print_chunks (ch):
555         for c in ch:
556                 print '-->%s\n%s' % (c[0], c[1])
557                 if len (c) > 2:
558                         print '==>%s' % list (c[2:])
559         print foo
560
561
562 def transform_input_file (in_filename, out_filename):
563         """Read the input, and deliver a list of chunks
564         ready for writing.
565         """
566
567         chunks = read_doc_file (in_filename)
568
569         #.  Process \mudela and \mudelafile.
570         for func in [find_mudela_shorthand_chunks,
571                      find_mudela_chunks]:
572                 newchunks = []
573                 for c in chunks:
574                         if c[0] == 'input':
575                                 newchunks = newchunks + func (c[1])
576                         else:
577                                 newchunks.append (c)
578                 chunks = newchunks
579
580         opts = []
581         if chunks:
582                 opts = scan_preamble (chunks[0][1]) 
583         
584         (chap,sect,count) = (0,0,0)
585         newchunks = []
586         # Count sections/chapters.
587         for c in chunks:
588                 if c[0] == 'input':
589                         (chap,sect,count) = advance_counters((chap,sect,count), opts, c[1])
590                 elif c[0] == 'mudela':
591                         base = '%s-%d.%d.%d' % (out_filename, chap, sect, count)
592                         count = count + 1
593                         c = schedule_mudela_block (base, c, opts)
594                         
595                 newchunks.append (c)
596
597         chunks = newchunks
598         newchunks = []
599
600
601         # Do It.
602         if not __main__.no_lily:
603                 compile_all_files (chunks)
604                 
605                 # finishing touch.
606                 for c in chunks:
607                         if c[0] == 'mudela' and 'eps' in c[2]: 
608                                 body = re.sub (r"""\\mudelaepswidth{(.*?)}""", find_eps_dims, c[1])
609                                 newchunks.append (('mudela', body))
610                         else:
611                                 newchunks.append (c)
612
613                 if chunks and chunks[0][0] == 'input':
614                         chunks[0] = ('input', completize_preamble (chunks[0][1]))
615                 
616         return chunks
617
618 def system (cmd):
619         sys.stderr.write ("invoking `%s'\n" % cmd)
620         st = os.system (cmd)
621         if st:
622                 sys.stderr.write ('Error command exited with value %d\n' % st)
623         return st
624
625 def compile_all_files (chunks):
626         eps = []
627         tex = []
628         png = []
629
630         for c in chunks:
631                 if c[0] <> 'mudela':
632                         continue
633                 base  = c[3][0]
634                 exts = c[3][1:]
635                 for e in exts:
636                         if e == 'eps':
637                                 eps.append (base)
638                         elif e == 'tex':
639                                 tex.append (base + '.ly')
640                         elif e == 'png':
641                                 png.append (base)
642
643         if tex:
644                 lilyopts = map (lambda x:  '-I ' + x, include_path)
645                 lilyopts = string.join (lilyopts, ' ' )
646                 texfiles = string.join (tex, ' ')
647                 system ('lilypond %s %s' % (lilyopts, texfiles))
648
649         for e in eps:
650                 cmd = r"""tex %s; dvips -E -o %s %s""" % \
651                       (e, e + '.eps', e)
652                 system (cmd)
653
654         for g in png:
655                 cmd = r"""gs -sDEVICE=pgm  -dTextAlphaBits=4 -dGraphicsAlphaBits=4  -q -sOutputFile=- -r90 -dNOPAUSE %s -c quit | pnmcrop | pnmtopng > %s"""
656
657                 cmd = cmd % (g + '.eps', g + '.png')
658                 system (cmd)
659
660         
661 def update_file (body, name):
662         same = 0
663         try:
664                 f = open (name)
665                 fs = f.read (-1)
666                 same = (fs == body)
667         except:
668                 pass
669
670         if not same:
671                 f = open (name , 'w')
672                 f.write (body)
673                 f.close ()
674
675         
676         return not same
677
678
679
680 def getopt_args (opts):
681         "Construct arguments (LONG, SHORT) for getopt from  list of options."
682         short = ''
683         long = []
684         for o in opts:
685                 if o[1]:
686                         short = short + o[1]
687                         if o[0]:
688                                 short = short + ':'
689                 if o[2]:
690                         l = o[2]
691                         if o[0]:
692                                 l = l + '='
693                         long.append (l)
694         return (short, long)
695
696 def option_help_str (o):
697         "Transform one option description (4-tuple ) into neatly formatted string"
698         sh = '  '       
699         if o[1]:
700                 sh = '-%s' % o[1]
701
702         sep = ' '
703         if o[1] and o[2]:
704                 sep = ','
705                 
706         long = ''
707         if o[2]:
708                 long= '--%s' % o[2]
709
710         arg = ''
711         if o[0]:
712                 if o[2]:
713                         arg = '='
714                 arg = arg + o[0]
715         return '  ' + sh + sep + long + arg
716
717
718 def options_help_str (opts):
719         "Convert a list of options into a neatly formatted string"
720         w = 0
721         strs =[]
722         helps = []
723         for o in opts:
724                 s = option_help_str (o)
725                 strs.append ((s, o[3]))
726                 if len (s) > w:
727                         w = len (s)
728
729         str = ''
730         for s in strs:
731                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
732         return str
733
734 def help():
735         sys.stdout.write("""Usage: mudela-book [options] FILE\n
736 Generate hybrid LaTeX input from Latex + mudela
737 Options:
738 """)
739         sys.stdout.write (options_help_str (options))
740         sys.stdout.write (r"""Warning all output is written in the CURRENT directory
741
742
743
744 Report bugs to bug-gnu-music@gnu.org.
745
746 Written by Tom Cato Amundsen <tomcato@xoommail.com> and
747 Han-Wen Nienhuys <hanwen@cs.uu.nl>
748 """)
749
750         sys.exit (0)
751
752
753 def write_deps (fn, target,  deps):
754         sys.stdout.write('writing `%s\'\n' % fn)
755
756         f = open (fn, 'w')
757         
758         target = target + '.latex'
759         f.write ('%s: %s\n'% (target, string.join (deps, ' ')))
760         f.close ()
761
762                 
763 def identify():
764         sys.stdout.write ('mudela-book (GNU LilyPond) %s\n' % program_version)
765
766 def print_version ():
767         identify()
768         sys.stdout.write (r"""Copyright 1998--1999
769 Distributed under terms of the GNU General Public License. It comes with
770 NO WARRANTY.
771 """)
772
773
774 def main():
775         global outdir, initfile, defined_mudela_cmd, defined_mudela_cmd_re
776         outname = ''
777         try:
778                 (sh, long) = getopt_args (__main__.options)
779                 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
780         except getopt.error, msg:
781                 sys.stderr.write("error: %s" % msg)
782                 sys.exit(1)
783
784         do_deps = 0
785         for opt in options:     
786                 o = opt[0]
787                 a = opt[1]
788                 
789                 if o == '--include' or o == '-I':
790                         include_path.append (a)
791                 elif o == '--version':
792                         print_version ()
793                         sys.exit  (0)
794
795                 elif o == '--format' or o == '-o':
796                         __main__.format = a
797                 elif o == '--outname' or o == '-o':
798                         if len(files) > 1:
799                                 #HACK
800                                 sys.stderr.write("Mudela-book is confused by --outname on multiple files")
801                                 sys.exit(1)
802                         outname = a
803                 elif o == '--outdir' or o == '-d':
804                         outdir = a
805                 elif o == '--help' or o == '-h':
806                         help ()
807                 elif o == '--no-lily' or o == '-n':
808                         __main__.no_lily = 1
809                 elif o == '--dependencies':
810                         do_deps = 1
811                 elif o == '--default-mudela-fontsize':
812                         default_music_fontsize = string.atoi (a)
813                 elif o == '--init':
814                         initfile =  a
815         
816         identify()
817
818         for input_filename in files:
819                 file_settings = {}
820                 if outname:
821                         my_outname = outname
822                 else:
823                         my_outname = os.path.basename(os.path.splitext(input_filename)[0])
824                 my_depname = my_outname + '.dep'                
825
826                 chunks = transform_input_file (input_filename, my_outname)
827                 
828                 foutn = my_outname + '.' + format
829                 sys.stderr.write ("Writing `%s'\n" % foutn)
830                 fout = open (foutn, 'w')
831                 for c in chunks:
832                         fout.write (c[1])
833                 fout.close ()
834
835                 if do_deps:
836                         # write_deps (my_depname, my_outname, deps)
837                         sys.stderr.write ("--dependencies broken")
838
839 main()
840
841
842
843 #
844 # Petr, ik zou willen dat ik iets zinvoller deed,
845 # maar wat ik kan ik doen, het verandert toch niets?
846 #   --hwn 20/aug/99