#!/bin/csh

if ( ! -e berry ) then
  mkdir berry
endif

cd berry

if ( x$1 != "x-ex" ) then

source ~/.ezvasp.rc
cp -f ../str_relax.out str_hint.out
runstruct_vasp -nr -w vasp_berry.wrap
cp -f INCAR INCAR.berry
grep -i -v -e LBERRY -e NPPSTR -e DIPOL INCAR.berry > INCAR
$* $VASPCMD >& vaspc.out

foreach axis ( 1 2 3 )
  runstruct_vasp -nr -w vasp_berry.wrap
  echo IGPAR  =  $axis >> INCAR
  $* $VASPCMD >& vasp${axis}.out
  cp -f OUTCAR OUTCAR_berry_$axis
end

endif

set volume=`getvalue "volume of cell" < OUTCAR | tail -n -1`
grep '<R>' OUTCAR_berry_? | getlines -bt 'Berry-Phase' 'ionic' | grep electron | sed 's/,//g' | awk '{x+=$4; y+=$5; z+=$6}; END {s=1.602176e-19*1e20/'$volume'; printf "%7.4f %7.4f %7.4f\n",s*x,s*y,s*z;}' >! ../dipol.out
