#!/usr/bin/env python

# unfinished script that create a lilypond-book document
# over all the lessonfiles.

import sys, re, string, os, os.path
sys.path.append(".")

import src, src.dataparser, src.lessonfile

def so2ly(s, musicformat):
    re_staff = re.compile("\\\\staff")
    re_addvoice = re.compile("\\\\addvoice")
    v = re_staff.split(s)
    v = filter(lambda i: i!="", v)
    v = map(lambda s, r=re_addvoice: r.split(s), v)
    retval = "\\score{\n  <"
    i = ''
    for s in v:
        i = i + 'i'
        retval = retval + "\n    \\context Staff=%s<" % i
        for vo in s:
            i = i + 'i'
            if musicformat == 'chord':
                m = "< %s >" % vo
            else:
                m = vo
            retval = retval + "\n      \\context Voice=%s\\notes{%s}" % (i, m)
        retval = retval + "\n    >"
    retval = retval + "\n  >\n}"
    return retval

predef = {'dictation': 'dictation',
                      'progression': 'progression',
                      'harmony': 'harmony',
                      'sing-chord': 'sing-chord',
                      'chord': 'chord',
                      'id-by-name': 'id-by-name',
                      'satb': 'satb',
                      'horiz': 'horiz',
                      'vertic': 'vertic',
                      'yes': 1,
                      'no': 0,
                      'tempo': (60, 4)}

parser = src.dataparser.Dataparser(predef, ('tempo',))
parser.parse_file(sys.argv[1])
questions = map(lambda e: e[1],
                               filter(lambda e: e[0] == 'question',
                                      parser.m_blocks[1:]))
H = map(lambda e: e[1], filter(lambda e: e[0] == 'header',
                                       parser.m_blocks))
header = src.lessonfile._Header(H[0])


of = open(os.path.basename(sys.argv[1])+".tex", "w")
of.write(r"""\documentclass[a4paper, 12pt]{article}
\begin{document}
""")
of.write("\n\\begin{itemize}")
of.write("\n\\item title: %s" % header.title)
of.write("\n\\item description: %s" % header.description)
of.write("\n\\item content: %s" % header.content)
of.write("\n\\item musicformat: %s" % header.musicformat)
of.write("\n\\end{itemize}")

for q in questions:
    of.write("""\n\n\\section{Question: %s}
\\begin{lilypond}
%s
\\end{lilypond}
""" % (q['name'], so2ly(q['music'], header.musicformat)))
of.write("\n\\end{document}")
of.close()

