# This script takes the markdown file generated by pandoc from TeX files
# and reformats a few details of the file, so that Doxygen can render it.

import re

# Open existing file
with open('theory.md') as f:
    text = f.read()

# Replace @ sign by \cite commands
text = text.replace( '@', '\cite ' )

# Replace inline math by proper math for Doxygen
text = text.replace( r'$$\begin{aligned}', r'\f{eqnarray*}{' )
text = text.replace( r'\end{aligned}$$', r'\f}' )
text = re.sub( r'\$\$[\s$]*\n', r'\\f]\n', text )
text = text.replace( r'$', r'\f$' )

# Replace figures commands by the proper Doxygen equivalent
# The regex below detects the caption and filename and swap their order 
# (Required by Doxygen)
text = re.sub( r'\!\[\\\[fig:.+?\\\](?P<caption>.+?)\]\((?P<filename>.+?)\)',
               r'\image html \g<filename> "\g<caption>"', text )

# Add header and footer for Doxygen
text = '/** @page "Theory"\n\n' + text + '\n*/\n'

# Write this to the page directory
with open('./theory.txt', 'w') as f:
    f.write( text )
