#!/usr/bin/env python
# Script to convert slides done in markdown to latex

import os
import sys

fn = os.path.abspath('./commission_20080218.tex')
tmpdir = os.path.abspath('./build')

import re
def normal2slides(latex):
    slides = latex
    pat1 = re.compile('^', re.M)
    slides = re.sub(pat1, '  ', slides)
    slides = slides.replace('\\section{', '\\frametitle{')
    pat2 = re.compile('(^\s*\n)*frametitle{', re.M)
    slides = re.sub(pat2, 'XXXXXXX', slides)
    slides = slides.replace('  \\XXXXXXX',
            '\\end{frame}\n\n\\begin{frame}\n  \\frametitle{')
    slides += '\n\\end{frame}'
    count = 0
    for ch in slides:
        if ch == '\n' or ch == ' ':
            count += 1
        else:
            break
    slides = slides[count+12:]
    return slides

def test_normal2slides():
    in1 = \
r'''
\section{What's our aim}

\begin{itemize}
\item It's ``value": what economists term utility
\end{itemize}

\section{What do we mean by value?}

\begin{itemize}
\item What economist's mean by utility
\item Important to bear in mind: this is \emph{not} about money
\end{itemize}
'''
    exp = \
r'''
\begin{frame}

  \frametitle{What's our aim}
  
  \begin{itemize}
  \item It's ``value": what economists term utility
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{What do we mean by value?}
  
  \begin{itemize}
  \item What economist's mean by utility
  \item Important to bear in mind: this is \emph{not} about money
  \end{itemize}
\end{frame}
'''
    out = normal2slides(in1)
    print out
    assert out == exp

if __name__ == '__main__':
    import optparse
    usage = \
'''%prog <action>'''
    parser = optparse.OptionParser(usage)
    options, args = parser.parse_args()
    if len(args) > 0:
        action = args[0]
    else:
        action = ''
    if action == 'build':
        cmd = 'pdflatex --output-dir %s %s' % (tmpdir, fn) 
        os.system(cmd)
    elif action == 'mkdn2latex':
        outfp = 'slides.tex'
        infp = 'slides.mkd'
        tmpfp = 'tmp.tex'
        cmd = 'mkdn2latex.py %s > %s' % (infp, tmpfp)
        os.system(cmd)
        slides = file(tmpfp).read()
        slides = normal2slides(slides)
        fo = file(outfp, 'w')
        fo.write(slides)
        fo.close()
    else:
        parser.print_help()

