import sys 
from os.path import basename, splitext, join as pjoin
from subprocess import Popen

class MixLyrics (object):
    """ Class for interleaving lyrics and notation """
    def __init__(self, delim="@@"):
        self.lyrics = []
        self.melody = []
        self.delim = delim

    def parse(self,s):
        for line in s.split('\n'):
            line=line.strip()
            if line.startswith(self.delim):
                self.lyrics.append(line[len(self.delim):])
            else:
                self.melody.append(line)

    def emitlyrics(self):
        return " ".join(self.lyrics)
    def emitmelody(self):    
        return " ".join(self.melody)

def template():
    return """
    \include "english-solfa.ly" %% english.ly modified to include solfa syllables
    \score {
        <<
        \\new Voice = "Sop" {
        \\autoBeamOn
        \\relative do' { %(sopmelody)s }
        }
        \\new Lyrics \lyricsto "Sop" { %(soplyrics)s }
        >>
    } 
    """  

def runlily(lymusic, lilyscript="lily"):
    """
    Write and process an .ly file with the same
    name as this script. 
    Args:
        'lymusic' is the lilypond code to process
        'lilyscript' is the name of your script 
            that processes .ly files.
    """
    pyname = basename(sys.argv[0])
    lyname = pjoin(splitext(pyname)[0] + '.ly')
    print >>file(lyname,'w'), lymusic
    cmd = "%(lilyscript)s %(lyname)s"%locals()
    p = Popen(cmd, shell=True)  
    p.wait()  




