keep_tags = set(['thm', 'thm*', 'lem', 'lemma', 'pro', 'cor', '*thm',
                     'scholium', 'question', 'exercise', 'statement',
                     'normlemma', 'HBthm', 'ASthm', 'urysohn', 'Tietze',
                     'LebesgueNumThm', 'UrysohnMetrization', 'Bing',
                     'Nagata-Smirnov', 'Cantor\'s Theorem', 'Tychonoff\'s Theorem',
                     'Zorn', 'AxChoice', 'WellOrPrin', 'Continuum'])

removal_tags = set(['sol', 'hint', 'opt'])



filename = raw_input('Enter the filename (without .tex suffix): ')
#write_filename = raw_input('Enter the filename to write to: ')
write_filename = filename + '-thms.tex'
filename = filename + '.tex'

tex_string = ''.join([i for i in open(filename).readlines()])


final_string = ''


## Special case out the document class since it's slightly different than the rest.
#while not tex_string.startswith('\\documentclass['):
#    tex_string = tex_string[1:]

#end_index = 0
#while tex_string[end_index] != ']':
#    end_index += 1

#final_string += tex_string[:end_index + 1] + '\n\\begin{document}\n\n'
#tex_string = tex_string[end_index:]


while len(tex_string) > 0:
    if tex_string.startswith('%'):
        end_index = 0
        while tex_string[end_index] != '\n':
            end_index += 1
        tex_string = tex_string[end_index:]
    if tex_string.startswith('\\chapter{'):
        end_index = 0
        while tex_string[end_index] != '}':
            end_index += 1
        final_string += tex_string[:end_index + 1] + '\n\n'
        tex_string = tex_string[end_index:]
    if tex_string.startswith('\\begin{'):
        for env in keep_tags:
            if tex_string.startswith('\\begin{' + env + '}'):
                end_index = 1
                while not tex_string[:end_index].endswith('\\end{' + env + '}'):
                    end_index += 1
                theorem_statement = tex_string[:end_index]
                # Now remove hint, sol, opt from the body
                for rem in removal_tags:
                    while '\\begin{' + rem + '}' in theorem_statement:
                        low_index = theorem_statement.find('\\begin{' + rem + '}')
                        high_index = theorem_statement.find('\\end{' + rem + '}') + 6 + len(rem)
                        theorem_statement = theorem_statement[:low_index] + theorem_statement[high_index:]
                        
                final_string += theorem_statement + '\n\n\\oneperpage\n\n'
                tex_string = tex_string[end_index - 1:]
                break
    tex_string = tex_string[1:]


#final_string += '\\end{document}'

write_file = open(write_filename, 'w+')
write_file.write(final_string)
write_file.close()


