#!/usr/bin/env python2                                                                                                                       

import sys

atom = sys.argv[1]
number = sys.argv[2]
basis  = sys.argv[3]
method = sys.argv[4]

filemethod = "data_"+method+"_"+basis
fileexact = "exact-"+atom+number
distance = []
wf = []
pbe = []
pbeot = []
pbeotnospin = []

ndistances=0
with open(filemethod, "r") as fp:
   for line in fp:
     a=line.split()
     if(len(a)==0):
      pass
     elif("#" in a[0]):
      pass
     else:
      distance.append(float(a[0]))
      wf.append(float(a[1]))
      pbe.append(float(a[2]))
      pbeot.append(float(a[3]))
      pbeotnospin.append(float(a[4]))
      ndistances += 1

print ndistances
wf_at = wf[ndistances-1]
pbe_at = pbe[ndistances-1]
pbeot_at = pbeot[ndistances-1]
pbeot_atnospin = pbeotnospin[ndistances-1]
ndistancesexact=0
exact = []
with open(fileexact, "r") as fp:
   for line in fp:
     a=line.split()
     if(len(a)==0):
      pass
     elif("#" in a[0]):
      pass
     else:
      exact.append(float(a[1]))
      ndistancesexact += 1

exact_at = exact[ndistances-1]
print ndistancesexact

wf_pbe = []
wf_pbeot = []
wf_pbeotnospin = []
relat_wf = []
relat_pbe = []
relat_pbeot = []
relat_pbeotnospin = []
relat_exact = []
error_wf = []
error_pbe = []
error_pbeot = []
error_pbeotnospin = []

for i in range(ndistances):
  wf_pbe.append(wf[i] + pbe[i]) 
  wf_pbeot.append(wf[i] + pbeot[i])
  wf_pbeotnospin.append(wf[i] + pbeotnospin[i])
  relat_wf.append(wf[i] - wf_at)
  relat_pbe.append(wf_pbe[i] - wf_at- pbe_at)
  relat_pbeot.append(wf_pbeot[i] - wf_at - pbeot_at)
  relat_pbeotnospin.append(wf_pbeotnospin[i] - wf_at - pbeot_atnospin)
  relat_exact.append(exact[i] - exact_at)
  error_wf.append(wf[i] - exact[i])
  error_pbe.append(wf_pbe[i] - exact[i])
  error_pbeot.append(wf_pbeot[i] - exact[i])
  error_pbeotnospin.append(wf_pbeotnospin[i] - exact[i])
  

file_data=filemethod+"E_tot"
file_output = open(file_data,"w+")
file_data_relat=filemethod+"E_relat"
file_data_error=filemethod+"E_error"
file_output_relat = open(file_data_relat,"w+")
file_output_error = open(file_data_error,"w+")
for i in range(ndistances):
  file_output.write(str(distance[i]) +'  '+str(wf[i]) + '   ' + str(wf_pbe[i]) + '  ' + str(wf_pbeot[i]) + '  ' + str(wf_pbeotnospin[i]) + '  ' + str(exact[i])   +'\n')
  file_output_relat.write(str(distance[i]) +'  '+str(relat_wf[i]) + '   ' + str(relat_pbe[i]) + '  ' + str(relat_pbeot[i]) + '  ' + str(relat_pbeotnospin[i]) + '  '+  str(relat_exact[i])   +'\n')
  file_output_error.write(str(distance[i]) +'  '+str(error_wf[i]) + '   ' + str(error_pbe[i]) + '  ' + str(error_pbeot[i])   +'  ' + str(error_pbeot[i])  +  '\n')