import fileinput
import os
psblock = False
pscode = ''
jscode = ''
with open("source.js", "r", encoding="utf-8") as f:
    for line in f:
        if psblock == False:
            if "/** -*-PureScript Code -*-" in line:
                psblock = True
                jscode = jscode + "//athere"
            else:
                jscode = jscode + line
        else:
            if "**/" in line:
                psblock = False
                continue
            else:
                pscode = pscode + line

with open("Main.purs", "w", encoding="utf-8") as f:
    f.write(pscode)
with open("newcode.js", "w", encoding="utf-8") as f:
    f.write(jscode)

os.system("cp Main.purs ../ps_mod/src/")
os.system("pulp -b ../ps_mod/bower.json build")
os.system("cp ../ps_mod/output/Main/index.js ./")

for line in fileinput.input('newcode.js', backup='.bak',inplace = True):
    if '//athere' in line:
        with open("index.js", "r", encoding="utf-8") as f:
            for tmpLine in f:
                if "// Generated by purs version" in tmpLine:
                    print("// Generated safe typed JS code by YapuresPlus")
                else:
                    print(tmpLine)
    else:
        print(line.rstrip())
