with open('gerda_malaperis_copy_pasted.txt') as f:
    lines = f.readlines()
currentLine = ""
fixed = []
fixed.append("% Gerda Malaperis\n% Claude Piron")
for i, line in enumerate(lines):
    if i < 2:
        continue

    line2 = lines[i-2].strip()
    line1 = lines[i-1].strip()

    if len(line) > 1:
        if line[0] == "#":
            fixed.append(line.strip())

    if line2 != "":
        if line2[0] != "#" and line1 == "" and line.strip() != "":
            currentLine = currentLine + " " + line.strip()
        if line2[0] == "#":
            currentLine = line.strip()

    if line2 == "":
        if line.strip() != "":
            currentLine = line.strip()
        if line.strip() == "" and line1 == "":
            if currentLine != "":
                fixed.append(currentLine)
                currentLine = ""
with open("gerda_malaperis.txt", "w") as f:
    for line in fixed:
        f.write(line)
        f.write("\n\n")
