#!/usr/bin/env python3

import glob
import fileinput
from titlecase import titlecase


def list_tex_files():
    files = list(glob.iglob('*.tex'))
    files.extend(list(glob.iglob('**/*.tex')))
    return files


def is_heading(line):
    patterns = ["\\chapter", "\\section", "\\subsection", "\\subsubsection"]
    return any([line.startswith(pattern) for pattern in patterns])


def titlecase_heading(heading):
    tc = titlecase(heading)
    return tc[:2].lower() + tc[2:]


for filename in list_tex_files():
    with open(filename, 'r') as file:
        file_content = file.read()

    lines = file_content.splitlines()

    for i in range(0, len(lines)):
        line = lines[i]

        if is_heading(line):
            lines[i] = titlecase_heading(line)

    with open(filename, 'w') as file:
        file.write("\n".join(lines) + "\n")
