################################################################################
## Add Class Module ############################################################
import sys
import os
import os.path
import string
from numpy import *
from numpy.linalg import *
#from LinearAlgebra import *
#from Numeric import *
sys.path.append("./UserModule/Common")
sys.path.append("./UserModule/LMF")
from Converter import Converter
from addSite import *
from RemoveTaggedSection import RemoveTaggedSection

def ConvertTagSec(s,seckey):
# For convert Tag Section with CLASS keyword.
	if string.find(s,"TYPE")>=0:	# KeyWord: Class
		n	= string.count(s, ",")
		st	= string.split(s)
								#	remove keyword TYPE
		Eq	= string.split(string.join(st[2:]),",")	#
		ClassName	=	st[1]
		outdata = ""
		for i in range(n+1):
			EqP = string.split(Eq[i],"=")
			data = string.replace(string.strip(EqP[1])," ","','")
			outdata	=	"Type['%s']['%s%s']='%s'" % (ClassName,string.strip(EqP[0]),seckey,data)

	else:
		outdata=s
	return outdata
	
def setpvecline(PV1,PV2,PV3,a):
# for setting primitive vector--- for older AkaiKKR.
# See cpa2002v005/source/prmvec.f
	pvecline= \
	"STRUC ALAT=%18.12f\n"  % a
	pvecline= pvecline + \
	"      PLAT=%18.12f %18.12f %18.12f\n           %18.12f %18.12f %18.12f\n           %18.12f %18.12f %18.12f"  % \
	(PV1[0]/a,PV1[1]/a,PV1[2]/a,
	 PV2[0]/a,PV2[1]/a,PV2[2]/a, 
	 PV3[0]/a,PV3[1]/a,PV3[2]/a)
	return pvecline

def Concsolve(atomconc):
	s = ""
	for key in atomconc.keys():
		s = s+"(%d:%s)" % (key, atomconc[key])

	atomconc = s
	atomconc = string.replace(atomconc,'(',' ')
	atomconc = string.split(atomconc+' end',')')[:-1]
	ncom =len(atomconc)
	comp=['None']*ncom
	conc=['None']*ncom
	for ic in range(ncom):
		comp[ic],conc[ic] = string.split(string.strip(atomconc[ic]),':')
		conc[ic]=string.atof(conc[ic])
#		print '%s %6.2f ' % (comp[ic], conc[ic]) 
	l_max=3
	return comp, conc,l_max,ncom

#############################################################
## Main Routinue ############################################
if __name__ == '__main__':
	
	### 1. User set CSY File PATH
	csyFilePath = "./temp/xxx.csy1"
	
	### 2. Create Conveter Object
	A = Converter(csyFilePath)

	exec A.script
	flog  = open("./result/ResultWindow.dat","wt")	
	enginekey='LMF'
	#Matlist	=	Type.keys()
	#fname = Matlist[0]+"_
	fname=''
	j=0
	for i in Type:
		if j==1:	fname =  fname + '_'
		fname = fname + i
		j=1
	fname=fname + '.inp'
	result=''
	err=''

### pvec lines
	pvecline = setpvecline(PV1,PV2,PV3,a)

### type lines ######################
	typeline=''
	for i in Type:
#		print i,Type[i]["ATOM"]
		comp,conc,l_max,ncom = Concsolve(Type[i]["ATOM"])

		head = '     ATOM=%s Z=%s ' %  (i,comp[0]) # comp[0:len(comp)]
		try: 
			head = head + ' LMX=%s ' %  (Type[i]['LMX'])
		except:
			pass
		try: 
			head = head + ' R=%s ' %  (Type[i]['RMT'])
		except:
			pass

		typeline= typeline + head + '\n' 

#		if(len(comp)-1):
#			for ix in range(1,):
#				typeline = typeline + ' '*len(head) + '  %s  \n' % ()


### site lines #######################
	if(abs(det(array([PV1,PV2,PV3])))<1e-6):
		err= 'Wrong input!: ====== PV are not linear independent ========= '
		flog.write(err)
#	mat= inverse(transpose(array([PV1,PV2,PV3])))
	siteline=''
	for i in range(SiteNum):
		pt=Site[i]['PosData']
		siteline= siteline + '     ATOM=%s POS=%18.12f %18.12f %18.12f \n' % (Site[i]["TYPE"],pt[0]/a,pt[1]/a,pt[2]/a)
# These are in unit of primitive vec
#		pt=matrixmultiply(mat	,Site[i]["PosData"])
#		siteline= siteline + '%18.12fa %18.12fb %18.12fc  %s \n' % (pt[0],pt[1]/,pt[2]/a,Site[i]["TYPE"])


#### main printing from here
	result= result + '''
#----Generated by XtalEdit ----------------------------------#
%s             
      NCLASS=%d NBAS=%d
CLASS
%s
SITE
%s
'''  % (pvecline, \
		TypeNum, SiteNum, typeline, siteline)

	print result
	flog.write(result)
