#!/bin/bash


# Data read direct from TiO2.castep_<>, so in units of eV/primitive unit cell.
# Anatase	4 TiO2
# Brookite	8 TiO2
# Columbite	4 TiO2
# Rutile	2 TiO2
### All energies converted to eV/(TiO2) on read.


for dir in Anatase Brookite Columbite Rutile
  do

  cd $dir



  rm -f .t1 ; touch .t1
  rm -f .t2 ; touch .t2
  rm -f .t0 .t3
  name=$( pwd | sed 's!.*/!!' )
  case $name in
      Anatase) ntio2_prim=4 ;;
     Brookite) ntio2_prim=8 ;;
    Columbite) ntio2_prim=4 ;;
       Rutile) ntio2_prim=2 ;;
  esac



  for noelec in     384 576 768
   do

    case $noelec in
      192) ntio2_super=8  ;;
      384) ntio2_super=16 ;;
      576) ntio2_super=24 ;;
      768) ntio2_super=32 ;;
    esac

### 1-BD correction & error estimate #############################################
    idx=0
    for func in lda pw91 pbe rpbe wc pbesol
      do

      file1='TiO2.castep_'$noelec'_'$func  ; file2='TiO2.castep_7_'$func
      set -- $( grep 'Total energy' $file1 | sed 's/^.*=//' ) ; efin=$1
      set -- $( grep 'Total energy' $file2 | sed 's/^.*=//' ) ; einf=$1
      x=$( echo '( ( '$einf' )-( '$efin' ) )/( '$ntio2_prim' )' | bc -l )
      crc1[$idx]=$x                        ; funcname[$idx]=$func
      if [ "$func" == "lda" ]              ; then crc1_lda=$x ; fi
      idx=$(($idx+1))

    done
    n=$(($idx-1)) ; num=$idx

    for ((i1=0;i1<=$n;++i1)); do
    for ((i2=0;i2<=$n;++i2)); do
     echo $( echo '( '${crc1[$i1]}' )-( '${crc1[$i2]}' )' | bc -l | sed 's/-//' ) ${funcname[$i1]} ${funcname[$i2]}
    done
    done > .t0
    set -- $( sort -k1 -n .t0 | tail -1 ) ; maxabsdiff1=$1
#   echo $2 $3
    rm .t0

    echo -e $ntio2_super'\t'$crc1_lda'\t'$maxabsdiff1 >> .t1


### Record some data for 2-BD correction (see below).
    file1='TiO2.castep_'$noelec'_lda' ; file2='TiO2.castep_'$noelec'_kzk'
    set -- $( grep 'Total energy' $file1 | sed 's/^.*=//' ) ; elda=$1
    set -- $( grep 'Total energy' $file2 | sed 's/^.*=//' ) ; ekzk=$1
    x=$( echo '( ( '$elda' )-( '$ekzk' ) )/( '$ntio2_prim' )' | bc -l )
    echo -e $ntio2_super'\t'$x >> .t2

  done


### 2-BD
### Record terms used for 2-bd FSC component in file, and fit to get estimate for error.
  rm -f fit.log ; cp .t2 .temp ; gnuplot '../fit.gnu' &> .t3 ; rm -f .temp
  set -- $( grep 'Fit N-' .t3  ) ; a=$4
  set -- $( grep 'Fit Ma' .t3  ) ; maxabsdiff2=$4




###  Combine the two into one files, with errors for 2-BD added as a new columns. Write to stdout.
  set -- $( wc -l .t1 ) ; nolines=$1
  echo '#'$name
  for ((i=1;i<=$nolines;++i)); do
    set -- $( sed -n $i'p' < .t1 ) ; sz=$1 ; fsc1=$2 ; e_fsc1=$3
    set -- $( sed -n $i'p' < .t2 ) ;         fsc2=$2 ; e_fsc2=$a
    echo -e $sz'\t'$fsc1'\t'$e_fsc1'\t'$fsc2'\t'$e_fsc2
  done
  echo



  rm -f .t0 .t1 .t2 .t3

  cd ..
done

