# Simple-minded reader for NAMD files

"""Reader for NAMD XSC format."""


import numpy as np
import simtk.unit as u
import simtk.openmm as mm

from simtk.unit.quantity import Quantity




def parse_xsc(xsc):
    with open(xsc) as f:
        for l in f:
            if '#' in l:
                continue
            ls = l.split(" ")
            if len(ls) >= 10:
                boxx = float(ls[1])
                boxy = float(ls[5])
                boxz = float(ls[9])
    return (boxx, boxy, boxz)


def parse_xsc_units(xsc):
    box = parse_xsc(xsc)
    boxa = mm.Vec3(box[0], 0., 0.) * u.angstrom
    boxb = mm.Vec3(0., box[1],  0.) * u.angstrom
    boxc = mm.Vec3(0., 0., box[2]) * u.angstrom
    return (boxa, boxb, boxc)


def write_xsc(xsc, step, stime, np_box):
    import time

    np_box=np_box.value_in_unit(u.angstrom)
    with open(xsc, "w") as f:
        f.write(f"# XSC file generated by miniomm for simulation time {stime} on {time.ctime()}\n")
        f.write("#$LABELS step a_x a_y a_z b_x b_y b_z c_x c_y c_z o_x o_y o_z\n")
        f.write(f"{step} ")
        f.write(" ".join(str(x) for x in np_box[0,:]))
        f.write("  ")
        f.write(" ".join(str(x) for x in np_box[1,:]))
        f.write("  ")
        f.write(" ".join(str(x) for x in np_box[2,:]))
        f.write("  ")
        f.write("0.0 0.0 0.0\n")
    
