import os

def slicer(string):
    out = []
    string = string.strip()
    string = string.split(" ")
    for i in string:
        if i != "":
            out.append(i)
    return out

def spacer(n_tot, string):
    out = ""
    for i in range(n_tot-len(string)):
        out = out + " "
    out = out + str(string)
    return out

# Declaration of some variables
filelist = []
orb = False

# Generation of output directory and paths
os.mkdir("Molden_Files")
o_path = os.getcwd()
n_path = (o_path + r"\Molden_Files")

# Generation of a list containing file names
for x in os.listdir():
    if x.endswith(".out"):
        filelist.append(x)
        
# Conversion and generation of MOLDEN files in the output directory
for x in filelist:
    o_file = open(x, "r")
    o_content = o_file.readlines()
    os.chdir(n_path)
    n_file = open(x[:-4] + ".molden", "w")
    n_content = ["[Molden Format]\n", "[Atoms] Angs\n"]
    i = 0
    while i < len(o_content):
        if "primitive gaussians" in o_content[i]:
            n_basis = int(slicer(o_content[i])[0])
        if "Symbolic Z-matrix:" in o_content[i]:
            k = 0
            while o_content[i+2+k] != " \n":
                line = slicer(o_content[i+2+k])
                if len(line[0]) == 1:
                    n_content.append(" " + line[0] + " ")
                else:
                    n_content.append(line[0] + " ")
                k = k+1
        if "Standard orientation:" in o_content[i]:
            k = 0
            while not("-----" in o_content[i+5+k]):
                line = slicer(o_content[i+5+k])
                n_content[2+k] = n_content[2+k] + spacer(5,line[0]) + " " + spacer(2,line[1]) + " " + spacer(12,line[3]) + " " + spacer(12,line[4]) + " " + spacer(12,line[5]) + "\n"
                k = k+1
        if "Standard basis:" in o_content[i]:
            std_basis = "[" + slicer(o_content[i])[3][1:-1]
            k = 4
            while k<len((slicer(o_content[i]))):
                std_basis = std_basis + slicer(o_content[i])[k][:-1]
                k = k+1
            n_content.append(std_basis + "]\n")
            n_content.append("[GTO]\n")
        if "AO basis set in the form of general basis input" in o_content[i]:
            k = 0
            while "\n" != o_content[i+1+k]:
                if "****" in o_content[i+1+k]:
                    n_content.append("  \n")
                else:
                    line = slicer(o_content[i+1+k])
                    if line[0].isnumeric():
                        n_content.append(spacer(3, line[0]) + " " + line[1] + "\n")
                    elif line[0].isalpha():
                        n_content.append(" " + line[0].lower() + spacer(5, line[1]) + " " + line[2] + "\n")
                    else:
                        n_content.append(spacer(18, line[0]) + spacer(18, line[1]) + "\n")
                k = k+1
            n_content.append("\n")
            n_content.append("[MO]\n")
        if "Molecular Orbital Coefficients:" in o_content[i]:
            orb = True
        if orb == True:
            if "Eigenvalues" in o_content[i]:
                orb_num = slicer(o_content[i-2])
                orb_occ = slicer(o_content[i-1])
                orb_ener = []
                orb_coeff = []
                for k in range(len(orb_num)):
                    orb_coeff.append([])
                line = slicer(o_content[i])
                for k in range(len(orb_num)):
                    orb_ener.append(o_content[i][(21+10*k):(31+10*k)])
                for k in range(n_basis):
                    line = slicer(o_content[i+1+k])
                    for j in range(len(orb_num)):
                        orb_coeff[j].append(line[-len(orb_num)+j])
                for k in range(len(orb_num)):
                    n_content.append(" Ene=" + spacer(11,orb_ener[k]) + "\n")
                    n_content.append(" Spin= Alpha\n")
                    if orb_occ[k] == "O":
                        n_content.append(" Occup=   2.000000\n")
                    else:
                        n_content.append(" Occup=   0.000000\n")
                    for j in range(n_basis):
                        n_content.append(spacer(len(str(n_basis)), str(j+1)) + spacer(10, orb_coeff[k][j]) + "0" + "\n")
                i = i+n_basis
        i = i+1
    n_file.writelines(n_content)
    o_file.close()
    n_file.close()
    print("The file " + x + " has been converted to Molden format")
    os.chdir(o_path)