import os
import sys
import shutil
import glob
import numpy as np
from numpy import sin, cos, tan, pi
import csv
from pprint import pprint


sys.path.append("d:/git/tkProg/tklib/python")


from tklib.tkfile import tkFile
from tklib.tkcrystal.tkcif import tkCIF
from tklib.tkcrystal.tkcrystal import tkCrystal
from tklib.tkcrystal.tkatomtype import tkAtomType


infile = 'COD/*.cif'
#infile = 'cif/*.cif'
#infile = 'test1.cif'
#infile = 'test.cif'
narg = len(sys.argv)
if narg >= 2:
    infile = sys.argv[1]

debug = 0
if narg >= 3:
    debug = int(sys.argv[2])

single = 1
findvalidstructure = 1
checklist = 'cifcheck.txt'
okdir = 'cif/ok'
#okdir = ''

print("infile: {}".format(infile))
print("single: {}".format(single))
print("findvalidstructure: {}".format(findvalidstructure))
print("checklist: {}".format(checklist))
print("debug: {}".format(debug))

def main():
    cout = tkFile(checklist, 'w')

    files = glob.glob(infile)
    
    for f in files:
        print("\nRead from [{}]".format(f))
        cout.Write("{}\n".format(f))

        cif = tkCIF()
        cif.debug = debug
    
#    atom = tkAtomType()
#    inf = atom.GetAtomInformation('Au')
#    for key in inf:
#        print("{}: {}".format(key, inf[key]))
#    print("")
#    exit()

        if single:
            cifdata = cif.ReadCIF(f, find_valid_structure = findvalidstructure)
            cifdata.Print()
            cry = cifdata.GetCrystal()
            print("")
            print("==============================================")
            cry.PrintInf()
            print("")
            print("==============================================")
            
            d = cry.Density()
            ad = cry.AtomDensity()
            if not (0.8 < d < 20.0):
                print("Error in [{}]: Too low or large density {} g/cm3".format(f, d))
                exit()
            if not (1.0e22 < ad < 10.0e23):
                print("Error in [{}]: Too low or large atom density {} /cm3".format(f, ad))
                exit()

            if okdir != '':
#                print("fp=", cif.fp)
#                cif.fp.close()
                print("move {} to {}".format(f, okdir))
                shutil.move(f, okdir)
#                shutil.copy2(f, okdir)
#                os.unlink(f)

            outfile = 'a.cif'
            cifdata.WriteSimpleCIFFile(outfile)
        
            outfile = 'b.cif'
            cifdata.CreateCIFFileFromCCrystal(cry, outfile)

#        pos0 = [0.3, 0.2, 0.1]
#        isym = 1
#        pos1 = cry.DoSymmetryOperation(pos0, isym)
#        print("pos0 ", pos0, " => sym %d" % (isym), pos1)
        else:
            cifdatas = cif.ReadCIFs(f)
            for cifdata in cifdatas:
                cifdata.Print()

        cif.Close()

    cout.Close()


if __name__ == "__main__":
    main()

