#!/bin/sh

# run from directory where this script is
cd `dirname $0`
EXAMPLE_DIR=`pwd`

# check whether ECHO has the -e option
if test "`echo -e`" = "-e" ; then ECHO=echo ; else ECHO="echo -e" ; fi

$ECHO
$ECHO "$EXAMPLE_DIR : starting"
$ECHO
$ECHO "This example shows how to use pw.x, pp.x, and average.x to"
$ECHO "compute the work function of a metal using the slab-supercell"
$ECHO "approximation.  This example is of a 4 layer unrelaxed Al(100) slab"
$ECHO "with 5 equivalent layers of vacuum between the surfaces."
$ECHO
$ECHO "The work function will be computed two ways:"
$ECHO "1) Calculating directly the difference between the potential in"
$ECHO "   the vacuum region and the Fermi energy of the slab."
$ECHO
$ECHO "2) By referencing the macroscopic average of the potential"
$ECHO "   of the interior of the slab to that of a bulk calculation, and"
$ECHO "   taking the difference of the V_vacuum of the slab and E_Fermi"
$ECHO "   of the bulk."
$ECHO
$ECHO "The work functions will be written in a file Al100.wf.data"
$ECHO "If gnuplot is detected, a plot will be generated Al100.wf.eps"

# set the needed environment variables
. ../../../environment_variables

# required executables and pseudopotentials
BIN_LIST="pw.x pp.x average.x"
PSEUDO_LIST=" Al.pbe-rrkj.UPF "


$ECHO
$ECHO "  executables directory: $BIN_DIR"
$ECHO "  pseudo directory:      $PSEUDO_DIR"
$ECHO "  temporary directory:   $TMP_DIR"
$ECHO "  checking that needed directories and files exist...\c"

# check for directories
for DIR in "$BIN_DIR" "$PSEUDO_DIR" ; do
    if test ! -d $DIR ; then
        $ECHO
        $ECHO "ERROR: $DIR not existent or not a directory"
        $ECHO "Aborting"
        exit 1
    fi
done
for DIR in "$TMP_DIR" "$EXAMPLE_DIR/results" ; do
    if test ! -d $DIR ; then
        mkdir $DIR
    fi
done
cd $EXAMPLE_DIR/results

# check for executables
for FILE in $BIN_LIST ; do
    if test ! -x $BIN_DIR/$FILE ; then
        $ECHO
        $ECHO "ERROR: $BIN_DIR/$FILE not existent or not executable"
        $ECHO "Aborting"
        exit 1
    fi
done

# check for gnuplot
GP_COMMAND=`which gnuplot 2>/dev/null`
if [ "$GP_COMMAND" = "" ]; then
        $ECHO
        $ECHO "gnuplot not in PATH"
        $ECHO "Results will not be plotted"
fi

# check for pseudopotentials
for FILE in $PSEUDO_LIST ; do
    if test ! -r $PSEUDO_DIR/$FILE ; then
       $ECHO
       $ECHO "Downloading $FILE to $PSEUDO_DIR...\c"
            $WGET $PSEUDO_DIR/$FILE $NETWORK_PSEUDO/$FILE 2> /dev/null
    fi
    if test $? != 0; then
        $ECHO
        $ECHO "ERROR: $PSEUDO_DIR/$FILE not existent or not readable"
        $ECHO "Aborting"
        exit 1
    fi
done
$ECHO " done"



# how to run executables
PW_COMMAND="$PARA_PREFIX $BIN_DIR/pw.x $PARA_POSTFIX"
PP_COMMAND="$PARA_PREFIX $BIN_DIR/pp.x $PARA_POSTFIX"
AVG_COMMAND="$BIN_DIR/average.x"
$ECHO
$ECHO "  running pw.x as:      $PW_COMMAND"
$ECHO "  running pp.x as:      $PP_COMMAND"
$ECHO "  running average.x as: $AVG_COMMAND"
$ECHO "  running gnuplot as:    $GP_COMMAND"
$ECHO

# self-consistent calculation for Al(100)
cat > Al100.in << EOF
&CONTROL
  calculation = "scf",
  pseudo_dir  = "$PSEUDO_DIR",
  outdir      = "$TMP_DIR",
/
&SYSTEM
  ibrav       = 6,
  celldm(1)   = 5.4235090117D0,
  celldm(3)   = 6.3639610306789276D0,
  nat         = 4,
  ntyp        = 1,
  ecutwfc     = 15.D0,
  occupations = "smearing",
  smearing    = "m-v",
  degauss     = 0.05D0,
  nr3         = 144,
/
&ELECTRONS
  conv_thr    = 1.D-10,
  mixing_beta = 0.7D0,
/

ATOMIC_SPECIES
Al  1.0  Al.pbe-rrkj.UPF

ATOMIC_POSITIONS alat
Al 0.00000000 0.00000000 4.2426406871192848
Al 0.50000000 0.50000000 3.5355339059327378
Al 0.00000000 0.00000000 2.8284271247461898
Al 0.50000000 0.50000000 2.1213203435596428

K_POINTS {automatic}
3 3 1 1 1 0
EOF
$ECHO "  running the scf calculation for Al(100) ...\c"
$PW_COMMAND < Al100.in > Al100.out
$ECHO " done"

# post-processing for potential
cat > Al100.pp.in << EOF
&inputPP
   outdir='$TMP_DIR',
   plot_num=11
   filplot = 'Al100.pot'
/

&plot
   iflag=3,
   output_format=3
/
EOF
$ECHO "  running pp.x to obtain 3D potential file ...\c"
$PP_COMMAND < Al100.pp.in > Al100.pp.out
$ECHO " done"

# calculating macroscopic averages of Au(100)
cat > Al100.avg.in <<EOF
1
Al100.pot
1.D0
1440
3
3.835000000
EOF
$ECHO "  Obtaining 1D macroscopic average of potential ...\c"
$AVG_COMMAND < Al100.avg.in > Al100.avg.out
$ECHO " done"

# copy file produced by average.x for later usage
mv avg.dat Al100.avg.dat

# self-consistent calculation for Al bulk ref
cat > Al.bulkref.in << EOF
&CONTROL
  calculation = "scf",
  pseudo_dir  = "$PSEUDO_DIR",
  outdir      = "$TMP_DIR",
/
&SYSTEM
  ibrav       = 1,
  celldm(1)   = 7.67000000D0,
  nat         = 4,
  ntyp        = 1,
  ecutwfc     = 25.D0,
  occupations = "smearing",
  smearing    = "m-v",
  degauss     = 0.05D0,
/
&ELECTRONS
  conv_thr    = 1.D-10,
  mixing_beta = 0.7D0,
/

ATOMIC_SPECIES
Al  1.0  Al.pbe-rrkj.UPF

ATOMIC_POSITIONS alat
Al   0.0000000      0.0000000      0.000000
Al   0.5000000      0.5000000      0.000000
Al   0.0000000      0.5000000      0.500000
Al   0.5000000      0.0000000      0.500000

K_POINTS {automatic}
3 3 3 1 1 1
EOF
$ECHO "  running the scf calculation for the Al bulk reference ...\c"
$PW_COMMAND < Al.bulkref.in > Al.bulkref.out
$ECHO " done"

# post-processing for potential
cat > Al.bulkref.pp.in << EOF
&inputPP
   outdir='$TMP_DIR',
   plot_num=11
   filplot = 'Albulkrefpot'
/

&plot
   iflag=3,
   output_format=3
/
EOF
$ECHO "  running pp.x to obtain 3D Bulk potential file ...\c"
$PP_COMMAND < Al.bulkref.pp.in > Al.bulkref.pp.out
$ECHO " done"

# calculating macroscopic averages of Au(100)
cat > Al.bulkref.avg.in <<EOF
1
Albulkrefpot
1.D0
25
3
7.67000000000
EOF
$ECHO "  Obtaining 1D macroscopic average of bulk potential ...\c"
$AVG_COMMAND < Al.bulkref.avg.in > Al.bulkref.avg.out
$ECHO " done"

# copy file produced by average.x for later usage
mv avg.dat Al.bulkref.avg.dat
# Extract the Fermi energies and V references
# script written specific to this example
eFermiSlab=`grep "Fermi" Al100.out | cut -d  \  -f 14`
eFermiBulk=`grep "Fermi" Al.bulkref.out | cut -d  \  -f 14`
vVac=`grep "0.000000000" Al100.avg.dat | cut -d  \  -f 13`
vBulk=`grep "0.000000000" Al.bulkref.avg.dat | cut -d  \  -f 12`
vSlab=`grep "17.8087" Al100.avg.dat | cut -d \  -f 10`
vVac=`awk "BEGIN{print $vVac*13.6058}"`
vBulk=`awk "BEGIN{print $vBulk*13.6058}"`
vSlab=`awk "BEGIN{print $vSlab*13.6058}"`
eFermiBulk=`awk "BEGIN{print $eFermiBulk-$vBulk+$vSlab}"`

wf1=`awk "BEGIN{ print $vVac-$eFermiSlab }"`
wf2=`awk "BEGIN{ print $vVac-$eFermiBulk }"`


#
#  if gnuplot was found, the results are plotted
#

if [ "$GP_COMMAND" = "" ]; then
    break
else
cat > gnuplot.tmp <<EOF
set term postscript eps enhanced
set output 'Al100.wf.eps'
set xr [0.0:18]
set yr [-12:9]
set ytics -12, 1, 9
set xlabel "Length (Angstroms)"
set ylabel "Energy (eV)"
# set key 11,6.5
set size sq 1,1
set label 1 "V_{Vacuum}" at 18.2, 5.4
set label 2 "E_{Fermi, Slab}" at 18.2, 1.6
set label 3 "E_{Fermi, Bulk}" at 18.2, 0.6
set label 4 "V_{Bulk}" at 18.2, -6.4
set label 5 "Work function calculated \n with no bulk reference \n {/Symbol F} = $wf1 eV" at 19, -0.7
set label 6 "Work function calculated \n with bulk reference \n {/Symbol F} = $wf2 eV" at 19, -4

plot 'Al100.avg.dat' using (\$1*0.52918):(\$3*13.6058) with lines linewidth 5 title 'V_{Macroscopic Average, Slab}', \
     'Al100.avg.dat' using (\$1*0.52918):(\$2*13.6058) with lines linewidth 1 title 'V_{Planar Average, Slab}', \
     $vSlab with lines linewidth 2 notitle, \
     $eFermiSlab with lines linewidth 2 notitle, \
     $eFermiBulk with lines linewidth 2 notitle

EOF
$ECHO "  Plotting averages and work function results ...\c"
$GP_COMMAND < gnuplot.tmp
$ECHO " done"
rm gnuplot.tmp
fi

$ECHO "  Writing work function results to file ...\c"
cat> Al100.wf.data <<EOF

The work function calculated without a bulk reference:
WF = $wf1

The work function calculated with a bulk reference:
WF = $wf2

EOF
$ECHO " done"

# clean TMP_DIR
$ECHO "  cleaning $TMP_DIR ...\c"
rm -rf $TMP_DIR/pwscf.*
$ECHO
$ECHO "$EXAMPLE_DIR: done"
