#! /bin/bash

#step 1: recompile dftd3 with user-defined set of D3(BJ) parameters for PBE
sed '/d3-gp start flag/q' dftd3/dftd3.f > dftd3/dftd3.f.tmp
a1=$(cat parameters | awk '{print $1}')
s8=$(cat parameters | awk '{print $2}')
a2=$(cat parameters | awk '{print $3}')
echo "              rs6 =$a1" >> dftd3/dftd3.f.tmp
echo "              s18 =$s8" >> dftd3/dftd3.f.tmp
echo "              rs18=$a2" >> dftd3/dftd3.f.tmp
tail -r dftd3/dftd3.f | sed '/d3-gp end flag/q' | tail -r >> dftd3/dftd3.f.tmp
mv dftd3/dftd3.f.tmp dftd3/dftd3.f
cd dftd3
make clean > /dev/null 2>&1
make > /dev/null 2>&1
echo " dftd3 has been successfully recompiled with user-defined set of"
echo "   D3(BJ) parameters for PBE."
cd ..

#step 2: initialize temporary database (raw.tmp)
rm -rf raw.tmp > /dev/null 2>&1
mkdir raw.tmp
for i in a b1 b2; do
  mkdir raw.tmp/$i
  mkdir raw.tmp/$i/mat
  mkdir raw.tmp/$i/cfp
done

#step 3: run dftd3 for database save matrix elements and fingerprint in raw.tmp
for i in $(ls ../data); do
  printf "$i/1248\r"
  for j in a b1 b2; do
    dftd3/dftd3 ../data/$i/$j/xyz -bj -func pbe -anal | sed -n '/pair  atoms/,/distance range/p' | tail -n+2 | tail -r | tail -n+3 | tail -r | awk '{print $7,$8}' > raw.tmp/$j/mat/$i
    dftd3/dftd3 ../data/$i/$j/xyz -bj -func pbe -anal | sed -n '/writing histogram/,/checksum (Edisp)/p' | tail -n+2 | tail -r | tail -n+2 | tail -r | awk '{print $7}' > raw.tmp/$j/cfp/$i
  done
done
rm histo.dat
echo " dftd3 matrix elements and fingerprints have been written to raw.tmp."
echo "   run maker.m next."
