"""
This script will post-process files generated by Sphinx to change some things.
"""

import os
import re

# directory of the source files
dir = "build/html/file"
class_dir = "build/html/class"

def fortran_replace_text(filename, filepath):
    """
    For some reason sphinx-fortran gets confused by the type 'double precision', so
    in preprocessing it was replaced with 'real'. Here, we shall switch it back
    to 'double precision'.

    Change 'Needed modules' -> "Required modules"
    """

    outtxt = ""
    with open(os.path.join(filepath, filename)) as infile:
        txt = infile.read()

        outtxt = re.sub(r"\[<\/em><em>real<\/em><em>", '[</em><em>double precision</em><em>', txt, flags=re.M)

        outtxt = re.sub("Needed modules", 'Required modules', outtxt, flags=re.M)

    with open(os.path.join(filepath, filename), 'w') as outfile:
        outfile.write(outtxt)

def replace_cpp_header_text(filename, filepath):
    """
    This removes amrex:: and std:: namespaces from the function prototypes
    to make them more readable.
    """

    outtxt = ""
    with open(os.path.join(filepath, filename)) as infile:
        txt = infile.read()

        outtxt = re.sub(r"amrex::", '', txt, flags=re.M)

        outtxt = re.sub("std::", '', outtxt, flags=re.M)

    with open(os.path.join(filepath, filename), 'w') as outfile:
        outfile.write(outtxt)


if __name__ == "__main__":

    # loop over files in dir
    for f in sorted(os.listdir(dir)):
        if f[-7:] == "_f.html":
            fortran_replace_text(f, dir)
        elif f[-8:] == "_8H.html":
            replace_cpp_header_text(f, dir)
            
    # loop over files in class_dir
    for f in sorted(os.listdir(class_dir)):
        replace_cpp_header_text(f, class_dir)
