#!/usr/bin/python
# -*- coding: latin1 -*-
#se charge de lire une structure d'output castep et la converti en fichier CIF

import sys,os
sys.path.append(os.getenv("HOME")+"/bin")

import libcif as C

if len(sys.argv)>1 : 
	if not os.path.isfile(sys.argv[1]):
		print "Veuillez entrer sur la ligne de commande le fichier CASTEP a transformer."
		sys.exit(1)
else:
		print "Castep2cif permet d'extraire la configuration d'une fichier d'output castep et régénère un fichier CIF. (sans sa symétrie) "
		sys.exit(1)

if len(sys.argv)==3 :
	if os.path.isfile(sys.argv[2]):
		print "Attention, le fichier de destination existe deja. je n'ai pas envie de l'écraser"
		sys.exit(1)
	
	outfile=sys.argv[2]
else:
	outfile=sys.argv[1].split(".")[0]+".cif"		
print "Converting %s ----> %s"%(sys.argv[1],outfile)
f=open(sys.argv[1]).readlines()
f.reverse()
cif={"_symmetry_cell_setting": "triclinic",
     "_symmetry_space_group_name_H-M":'P1',
     "_symmetry_Int_Tables_number" : "1",
     'loop_': [[['_symmetry_equiv_pos_site_id', '_symmetry_equiv_pos_as_xyz'],
            [{'_symmetry_equiv_pos_as_xyz': 'x,y,z',
              '_symmetry_equiv_pos_site_id': '1'}]]
			  ]}
key=['_atom_site_label','_atom_site_type_symbol','_atom_site_fract_x','_atom_site_fract_y','_atom_site_fract_z']
atoms=[]
for lin in f:
	line=lin.strip()
	if len(line)==0:continue
	if line=="Unit Cell":break
	if line.find("a =")==0:
		word=line.split()
		cif["_cell_length_a"]=word[2]
		cif["_cell_angle_alpha"]=word[5]
	if line.find("b =")==0:
		word=line.split()
		cif["_cell_length_b"]=word[2]
		cif["_cell_angle_beta"]=word[5]
	if line.find("c =")==0:
		word=line.split()
		cif["_cell_length_c"]=word[2]
		cif["_cell_angle_gamma"]=word[5]
	if line.find("Current cell volume =")==0:
		cif["_cell_volume"]=word=line.split()[4]
	if line[0]=="x":
		w=line.split()
		if len(w)==7 and w[0]=="x" and w[6]=="x":
			try:
				x=float(w[3])
				y=float(w[4])
				z=float(w[5])
			except:
				print w
				continue
			atoms.append({'_atom_site_type_symbol':w[1],'_atom_site_label':w[1]+w[2],'_atom_site_fract_x':w[3],'_atom_site_fract_y':w[4],'_atom_site_fract_z':w[5]})

cif["loop_"].append([key,atoms])
#print cif["loop_"][0][0]
#print sys.argv[1].split(".")[0]
print "Done"
C.SaveCIF(cif,outfile)
