#!/usr/bin/python
import os
import argparse
import re

START_SOLUTION_PATTERN = r'#>Solution'
END_SOLUTION_PATTERN = r'#<'

StartSolRec = re.compile(START_SOLUTION_PATTERN, re.M|re.I)
EndSolRec = re.compile(END_SOLUTION_PATTERN, re.M|re.I)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Exercise generation utility')
    parser.add_argument('file', help='text file the exercises are.')
    
    args = parser.parse_args()
    
    f = args.file
    
    assert os.path.isfile(f)
    
    filename, ext = os.path.splitext(f)
    
    of = filename+'_exercises'+ext
    
    lines = list()
    inSol = False
    with open(f, "r", encoding="utf-8") as ins:
        for line in ins:
            lines.append(line)
    
    with open(of, "w", encoding="utf-8") as outf:
        for line in lines:
            startSol = StartSolRec.search(line)
            if startSol:
                assert not inSol
                inSol = True
            
            if not inSol:
                outf.write(line)
            
            endSol = EndSolRec.search(line)
            if endSol:
                assert inSol
                inSol = False