#!/bin/bash
# use -x option for debug


# NOTE: For users who use this script first time
#   DO MIND TO Check '###?????###' sections and '#******** IMPORTANT *********' lines

HostName=`hostname`

#####???????????????#########################################
# EMail configuration: Edit  for your e-mail
#####???????????????#########################################
#******** IMPORTANT *********
#DoSendMail={DoSendMail}
DoSendMail=0
Title=`pwd`
Title=${Title##*/}
EMail=tkamiya@msl.titech.ac.jp
SMTPServer=lucid.msl.titech.ac.jp
Domain=lucid.msl.titech.ac.jp
MailerName=SendMail.pl:${ThisScript}.sh
From=$EMail

#####???????????????#########################################
# Parallelization configurations: Edit for your PC
#####???????????????#########################################
#******** IMPORTANT *********
nCPU=16
#NPAR=4
#KPAR=4
nCPUForMKL=1
nCPUForMKLDOS=16
MKL_NUM_THREADS=1
#MKL_NUM_THREADS=$nCPU
MPIParams="--Param:NPAR=$NPAR --Param:KPAR=$KPAR --Param:LPLANE=.TRUE."
#MPIParams="--Param:NPAR=$nCPU --Param:LPLANE=.TRUE."
#MPIParams=

#==========================================
# Define programs: Usually no need to edit
#==========================================
# Remote control daemon
rsysd="perl $HOME/bin/Perl/rsys/rsysdaemon.pl"

# Directories
MPIBIN=/usr/local/openmpi-intel131/bin
VASPDir=$TkPerlDir/VASP
VASPScriptDir=$VASPDir/script
RamanSCDir=$HOME/raman-sc

# Execute commands
PerlPATH=/usr/bin/perl
PythonPATH=python
#VASPPATH=/usr/local/VASP-5.3.5/bin/vasp
VASPPATH=/usr/local/VASP-5.4.1/bin/vasp_std
#VASPPATH=vasp

#VASP="bsub -n $nCPU $LSF_BINDIR/openmpi_wrapper -np $nCPU vasp"
VASP="$MPIBIN/mpirun -machinefile hosts -np $nCPU $VASPPATH"
#VASPDOS=$VASPPATH
#VASPDOS="$MPIBIN/mpirun -machinefile hosts -np $nCPU $VASPPATH"
VASPDOS="$MPIBIN/mpirun -machinefile hosts -np 1 $VASPPATH"
Usebsub=0
# VASPPhonopy is defined n DoPhonopyTemplate
VASPRaman=$VASP

export "CMD=$PerlPATH $VASPDir/VASP.pl"
export "PHONOPYplCMD=/usr/bin/perl $VASPDir/Phonopy.pl"
export "WIEN2kplCMD=$PerlPATH $TkPerlDir/WIEN2k/WIEN2k.pl"
#MakeCIFCMD=$HOME/bin/MakeCIFFile.sh
#MakeXSFCMD=$HOME/bin/MakeXSFFile.sh
MakeCIFCMD="$CMD --Action=ConvCONTCARFiles"
MakeSymmetrizedCIFCMD="$WIEN2kplCMD --Action=MakeSymmetrizedStructFile --TOL=0.001 *-final.cif out.struct"
MakeXSFCMD="$CMD --Action=MakeRelaxXSFFile --kMagnetization=0.8 --ArrowColor=255:0:0 --ArrowRadius=0.2"

#MXDFileConv=$HOME/bin/MXDFileConv.exe
#$MXDFileConv --Action=VASPConvCONTCAR --DBDir=${HOME}/bin/rietan --CalcRDF=0 --CoordinationNumber=4 $ARG1
#$MXDFileConv --Action=VASPMakeXSF     --DBDir=${HOME}/bin/rietan --CalcRDF=0 --CoordinationNumber=4 $ARGDIR/OUTCAR
CalIRCMD=$VASPScriptDir/CalIR.sh
CalRamanCMD=$RamanSCDir/vasp_raman.py
#DoPhonopyTemplatePath=$VASPScriptDir/DoPhonopy.sh
DoPhonopyTemplatePath=$VASPScriptDir/DoPhonopy-Template20160416.sh
DoPhonopyCMD=DoPhonopy.sh

# Utitlities
TEE=$HOME/bin/ktee

#====================================================
# Initialization: No need to edit
#====================================================
ThisScript=$0
BaseDir=`pwd`
OriginalDir=$BaseDir
WorkDir= 
ARGDIR=$BaseDir
ARG1=$ARGDIR/INCAR
Action=$1
Arg1=$2
Arg2=$3
Arg3=$4
Arg4=$5

#====================================================
# Invoke remote control daemon: No need to edit
#====================================================
$rsysd

#####???????????????#########################################
#####???????????????#########################################
#####???????????????#########################################
# MakeCIF parameters: Read carefully the 'IMPORTANT' lines and edit
#####???????????????#########################################
#####???????????????#########################################
#####???????????????#########################################
#******** IMPORTANT *********
# For hybrid functional calculation:
#   You must activate 'HybridFunctional' line.
# The other parameter lines even specific to hybrid calculation
# can leave activated also for DFT.

#SpinPolarized={SpinPolarized}
SpinPolarized=No
#SpinPolarized=Yes

CIFFile=auto
#UseConventionalCell={UseConventionalCell}
UseConventionalCell=No
#UseConventionalCell=Yes
##DefaultFunction=scf # Obsolete, not used
UseRecommendedPOTCAR=0
#UseRecommendedPOTCAR=Ba=Ba_sv,Si=Si,O=O_h
MakeCIFParams=

#DFT Functional=PAW_LDA54|PAW_PBE54|PAW_LDA52|PAW_PBE52|GGA|US|PAW|PAW_PBE
#Functional={Functional}
Functional=PAW_PBE54
#HybridFunctional=HF|HSE|PBE0
#HybridFunctional={HybridFunctional}
HybridFunctional=
#HybridFunctional=HSE
# Obsolete parameters, not used
##NKRED=2
##ISMEARHybridFunctional=1
##SIGMAHybridFunctionl=0.2

#####???????????????#########################################
# Tasks: Choose tasks as you like
#####???????????????#########################################
#Choose from '|MakeFilesFromCIF|MD|VCMD|VCRelaxRough|VCRelax|DFTSCF|SCF
#             |DOS|Band|ElectronDensity|Phonon|Phonopy|IR|Raman'
StopAfter=

# Set SkipIfDirectoryExists=1 if you do not want to repeat finished tasks
SkipIfDirectoryExists=1

MakeFilesFromCIF=1
BackUpOriginal=1

DoMD=0
DoVCRelaxRough=1
DoVCRelax=1
#Obsolete. Use AdditionalParameters=--NBANDS=x2 option
ChangeNBANDS=0
ChangeNELECT=0
# For hybrid calculations perform DFTSCF anyway
# For DFT DFTSCF is equal to SCF, should be DoDFTSCF=0
DoDFTSCF=1
if [ "$HybridFunctional" = "" ]; then
	DoDFTSCF=0
fi
DoSCF=1

# Note: CalculateDOS, CalculateBand and CalculatElectronDensity require DoSCF=1
#       CalculateBand (and CalculatedDOS etc) for hybrid requires DoDFTSCF=1
CalculateDOS=1
CalculateBand=0
CalculateElectronDensity=0

CalculatePhonon=1
# Note: CalculateIR and CalculateRaman require CalculatePhonon=1

DoPhonopy=1
# Note: Non-Analytical Term Correction requires CalculatePhonon=1
  DoPhonopyDOS=1
  DoPhonopyThermalProperties=1
  DoPhonopyPDOS=1
  DoPhonopyBand=1

CalculateIR=1
CalculateRaman=1

MakeSummary=1
DeleteExtraFiles=1
DeleteLargeFiles=1

#####???????????????#########################################
# SCF continuation switches: Usually no need to edit
#####???????????????#########################################
MDFromScratch=1
VCRelaxRoughFromScratch=0
VCRelaxFromScratch=0
DFTSCFFromScratch=1
SCFFromScratch=1
DOSFromScratch=0
eDensityFromScratch=0
PhononFromScratch=1

#####???????????????#########################################
#####???????????????#########################################
#####???????????????#########################################
# Common parameters: Read carefully the 'IMPORTANT' lines and edit
#####???????????????#########################################
#####???????????????#########################################
#####???????????????#########################################
PStress=0.0

#******** IMPORTANT *********
# For accurate tasks, VCRelax, SCF and postprocessors
# For phonon, EDIFF should be very small, EDIFFG should be negative and small
#   Typical values: EDIFF=1e-4, EDIFFG=1e-3 for DFT
#                   EDIFF=1e-4, EDIFFG=-1e-4 for phonon for 'normal' crystal
#                   EDIFF=1e-8, EDIFFG=-1e-5 for phonon for 'naive' crystal
EDIFF=1.0e-4
#EDIFF=1e-08
#EDIFF=1e-06
EDIFFG=1.0e-3
#EDIFFG=-1.0e-4
#EDIFFG=-1.0e-3

#******** IMPORTANT *********
# For phonon, use LREAL=.FALSE. and large ENCUT like 500 eV
# For usual DFT use default for ENCUT (comment out) and LREAL=Auto
AdditionalParameters="--Param:LREAL=Auto"
#AdditionalParameters="--Param:LREAL=Auto --NBANDS=x2"
#AdditionalParameters="--Param:LREAL=.FALSE. --NBANDS=64 --Param:SYMPREC=1e-4";
#AdditionalParameters="--Param:LREAL=Auto --NBANDS=64 --ENCUT=500"
#AdditionalParameters="--Param:LREAL=.FALSE. --ENCUT=500"

#####???????????????#########################################
# Common parameters after VCRelax
# For MD and VCRelaxRough, edit their sections
#####???????????????#########################################
# Precision: Accurate (High), Normal, Low
#PrecisionCommon={Precision}
PrecisionCommon=High
#PrecisionCommon=Accurate
#aKProductCommon=fix:{nkx},{nky},{nkz}
#aKProductCommon=2.5
aKProductCommon=2.0
#aKProductCommon=fix:3,3,3
#aKProductCommon=fix:8/2,8/2,6/3
#GammaOnlyCommon={GammaOnly}
GammaOnlyCommon=0
#ISMEARCommon={ISMEAR}
#ISMEARCommon=0
ISMEARCommon=-5
#SIGMACommon={SIGMA}
SIGMACommon=0.1
#SIGMACommon=0.01

# For hybrid: All, Diag, or Damped
# For others: Normal or Fast would be recommended
#ALGOCommon={ALGO}
ALGOCommon=Normal
#ALGOCommon=All
#ALGOCommon=Diag
#ALGOCommon=38
#ALGOCommon=48

#####???????????????#########################################
# Use *.klist file to plot band, specify 'File'
#####???????????????#########################################
BandKPoints1Common=File
#BandKPoints1=XG

#====================================================
# MakeCIF command
#====================================================
CMDMakeCIF="$CMD --Action=MakeINCAR --UseConventionalCell=$UseConventionalCell \
		 --UseRecommendedPOTCAR=$UseRecommendedPOTCAR --Function=scf \
		 --Functional=$Functional \
		 --HybridFunctional=$HybridFunctional \
		 $MPIParams $MakeCIFParams $AdditionalParameters \
		 --SpinPolarized=$SpinPolarized $CIFFile ./"
#		 --NKRED=$NKRED --ISMEARHybridFunctional=$ISMEARHybridFunctional \
#		 --SIGMAHybridFunctionl=$SIGMAHybridFunctionl \

#===========================================================
# Modification parameters: No need to edit unless you need
#===========================================================
RemoveAtom=
NBANDS=
NELECT=
CMDRemoveAtom="$CMD --Action=RemoveAtom --iRemoveAtom=$RemoveAtom ."
CMDChangeNBANDS="$CMD --Action=ModifyFiles --Function=scf --NBANDS=$NBANDS $ARG1"
CMDChangeNELECT="$CMD --Action=ModifyFiles --Function=scf --NELECT=$NELECT $ARG1"

#####???????????????#########################################
# MD parameters
#####???????????????#########################################
#MD|VCMD
MDMode=VCMD
InitializeVelocity=0
PrecisionMD=Norm
GammaOnlyMD=1
aKProductMD=1.5
#aKProductMD=fix:1/1,1/1,1/1
ALGO=53
ISMEARMD=1
SIGMAMD=0.1
KeepSymmetryMD=0
NSWMD=100
POTIM=5.0
SMASS=-1
NBLOCK=50
TEBEG=1000
TEEND=1000
EDIFFMD=3.0e-4
EDIFFGMD=5.0e-3
LELF=.FALSE.
CMDMD="$CMD --Action=ModifyFiles --Function=$MDMode \
		--InitializeVelocity=$InitializeVelocity \
		--HybridFunctional=$HybridFunctional --NKRED=$NKRED \
		 $MPIParams $MakeCIFParams \
		--Param:SMASS=-1 --Param:NBLOCK=$NBLOCK \ 
		--ISMEARHybridFunctional=$ISMEARHybridFunctional \
		--SIGMAHybridFunctionl=$SIGMAHybridFunctionl \
		--Precision=$PrecisionMD --Param:EDIFF=$EDIFFMD --Param:EDIFFG=$EDIFFGMD \
		--SpinPolarized=$SpinPolarized --PStress=$PStress \
		--Param:ISMEAR=$ISMEARMD --Param:SIGMA=$SIGMAMD \
		--Param:ALGO=$ALGO --Param:LELF=$LELF\
		--Param:NSW=$NSWMD --Param:POTIM=$POTIM --Param:TEBEG=$TEBEG --Param:TEEND=$TEEND \
		--GammaOnly=$GammaOnlyMD --aKProduct=$aKProductMD $AdditionalParameters \
		--KeepSymmetry=$KeepSymmetryMD --FromScratch=$MDFromScratch $ARG1"

#####???????????????#########################################
# VCRelaxRough parameters
#####???????????????#########################################
#RelaxModeRough=vc-relax|relax
RelaxModeRough=vc-relax
NSW=300
KeepSymmetryRough=1
#aKProductRough=fix:8/2,8/2,6/3
aKProductRough=1.5
GammaOnlyVCRelaxRough=0
ISMEARVCRelaxRough=-5
SIGMAVCRelaxRough=0.1
ALGO=$ALGOCommon
EDIFFRough=3.0e-4
EDIFFGRough=5.0e-3
LELF=.FALSE.
CMDVCRelaxRough="$CMD --Action=ModifyFiles --Function=$RelaxModeRough \
		--HybridFunctional=$HybridFunctional --NKRED=$NKRED \
		 $MPIParams \
		--ISMEARHybridFunctional=$ISMEARHybridFunctional \
		--SIGMAHybridFunctionl=$SIGMAHybridFunctionl \
		--Precision=Norm --Param:EDIFF=$EDIFFRough --Param:EDIFFG=$EDIFFGRough \
		--SpinPolarized=$SpinPolarized --PStress=$PStress \
		--Param:ISMEAR=$ISMEARVCRelaxRough --Param:SIGMA=$SIGMAVCRelaxRough \
		--Param:ALGO=$ALGO --Param:LELF=$LELF\
		--Param:NSW=$NSW \
		--GammaOnly=$GammaOnlyVCRelaxRough --aKProduct=$aKProductRough $AdditionalParameters \
		--KeepSymmetry=$KeepSymmetryRough --FromScratch=$VCRelaxRoughFromScratch $ARG1"

#####???????????????#########################################
# VCRelax parameters
#####???????????????#########################################
#RelaxMode=vc-relax|relax
RelaxMode=vc-relax
PrecisionVCRelax=$PrecisionCommon
KeepSymmetry=1
aKProductVCRelax=$aKProductCommon
GammaOnlyVCRelax=$GammaOnlyCommon
ISMEARVCRelax=$ISMEARCommon
SIGMAVCRelax=$SIGMACommon
ALGO=$ALGOCommon
LELF=.FALSE.
CommonParameters="--HybridFunctional=$HybridFunctional \
		 $MPIParams \
		--SpinPolarized=$SpinPolarized --PStress=$PStress"
#		 --NKRED=$NKRED --ISMEARHybridFunctional=$ISMEARHybridFunctional \
#		--SIGMAHybridFunctionl=$SIGMAHybridFunctionl \

CMDVCRelax="$CMD --Action=ModifyFiles --Function=$RelaxMode $CommonParameters \
		--Precision=$PrecisionVCRelax --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
		--Param:ISMEAR=$ISMEARVCRelax --Param:SIGMA=$SIGMAVCRelax \
		--Param:ALGO=$ALGO --Param:LELF=$LELF\
		--Param:NSW=$NSW \
		--GammaOnly=$GammaOnlyVCRelax --aKProduct=$aKProductVCRelax $AdditionalParameters \
		--KeepSymmetry=$KeepSymmetry --FromScratch=$VCRelaxFromScratch $ARG1"

#####???????????????#########################################
# SCF parameters
#####???????????????#########################################
Precision=$PrecisionCommon
aKProduct=$aKProductCommon
GammaOnly=$GammaOnlyCommon
ISMEAR=$ISMEARCommon
SIGMA=$SIGMACommon
ALGO=$ALGOCommon
CalOpticsSCF=0
CSHIFTSCF=0.1
# Obsolete: CalVibrationPhonon sets IBRION=8
#CalVibrationSCF=0
##IBRIONSCF=8
#LRPASCF=.FALSE.
LELF=.FALSE.

CMDDFTSCF="$CMD --Action=ModifyFiles --Function=scf \
	     --HybridFunctional= \
	     $MPIParams \
	     --SpinPolarized=$SpinPolarized --PStress=$PStress \
	     --Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
	     --Param:ISMEAR=$ISMEAR --Param:SIGMA=$SIGMA \
	     --Param:ALGO=$ALGO --Param:LELF=$LELF\
	     --GammaOnly=$GammaOnly --aKProduct=$aKProduct \
	     --CalOptics=$CalOpticsSCF --CSHIFT=$CSHIFTSCF \
	     --FromScratch=$SCFFromScratch \
	     $AdditionalParameters $ARG1"

CMDSCF="$CMD --Action=ModifyFiles --Function=scf \
	     $CommonParameters \
	     --Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
	     --Param:ISMEAR=$ISMEAR --Param:SIGMA=$SIGMA \
	     --Param:ALGO=$ALGO --Param:LELF=$LELF\
	     --GammaOnly=$GammaOnly --aKProduct=$aKProduct \
	     --CalOptics=$CalOpticsSCF --CSHIFT=$CSHIFTSCF \
	     --FromScratch=$SCFFromScratch \
	     $AdditionalParameters $ARG1"
#	     --CalVibration=$CalVibrationSCF --IBRION=$IBRIONSCF --LRPA=$LRPASCF \
#echo run [$CMDSCF]
#$CMDSCF

#####???????????????#########################################
# DOS parameters
#####???????????????#########################################
Precision=$PrecisionCommon
DOSNPAR=1
aKProductDOS=$aKProductCommon
GammaOnly=$GammaOnlyCommon
DOSISMEAR=$ISMEARCommon
DOSSIGMA=$SIGMACommon
RWIGSDB=RWIGS.ini
nMesh=5000
MinEnergy=-35.0
MaxEnergy=15.0
DOSWidth=0.01
ALGO=$ALGOCommon
CalOpticsDOS=0
CSHIFTDOS=0.01
# Obsolete: CalVibrationPhonon sets IBRION=8
#CalVibrationDOS=0
##IBRIONDOS=8
#LRPADOS=.FALSE.
LELF=.FALSE.
LVTOT=.FALSE.
LVHAR=.TRUE.

CMDDOS="$CMD --Action=ModifyFiles --Function=dos --Param:NPAR=$DOSNPAR --Param:LREAL=.FALSE. $CommonParameters \
		--Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
		--Param:ISMEAR=$DOSISMEAR --Param:SIGMA=$DOSSIGMA \
		--GammaOnly=$GammaOnly --aKProduct=$aKProductDOS \
		--Param:ALGO=$ALGO --Param:LELF=$LELF --Param:LVTOT=$LVTOT --Param:LVHAR=$LVHAR\
		--DOSMeasreudFromEF=1 --MinEnergy=$MinEnergy --MaxEnergy=$MaxEnergy --nMesh=$nMesh \
		--CalOptics=$CalOpticsDOS --CSHIFT=$CSHIFTDOS \
		--FromScratch=$DOSFromScratch \
		$AdditionalParameters"
#		--CalVibration=$CalVibrationDOS --IBRION=$IBRIONDOS --LRPA=$LRPADOS \

#####???????????????#########################################
# Band parameters
#####???????????????#########################################
# Set BandKPoints1=File to use *.klist file
Precision=$PrecisionCommon
NELMIN=5
BANDISMEAR=1
BANDSIGMA=0.1
BandKPoints1=$BandKPoints1Common
BandKPoints2=GY
BandKPoints3=GZ
nKPoint=51
ALGO=$ALGOCommon
LELF=.FALSE.
NELMIN=5
CMDBandX="$CMD  --Action=ModifyFiles --Function=band $CommonParameters \
		--Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
		--Param:ISMEAR=$BANDISMEAR --Param:SIGMA=$BANDSIGMA \
		--Param:ALGO=$ALGO --Param:LELF=$LELF $AdditionalParameters \
		--Param:NELMIN=$NELMIN \
		--GammaOnly=0 --nKPoint=$nKPoint --KPoints=$BandKPoints1"
CMDBandY="$CMD  --Action=ModifyFiles --Function=band $CommonParameters \
		--Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
		--Param:ISMEAR=$BANDISMEAR --Param:SIGMA=$BANDSIGMA \
		--Param:ALGO=$ALGO --Param:LELF=$LELF $AdditionalParameters \
		--Param:NELMIN=$NELMIN \
		--GammaOnly=0 --nKPoint=$nKPoint --KPoints=$BandKPoints2"
CMDBandZ="$CMD  --Action=ModifyFiles --Function=band $CommonParameters \
		--Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
		--Param:ISMEAR=$BANDISMEAR --Param:SIGMA=$BANDSIGMA \
		--Param:ALGO=$ALGO --Param:LELF=$LELF $AdditionalParameters \
		--Param:NELMIN=$NELMIN \
		--GammaOnly=0 --nKPoint=$nKPoint --KPoints=$BandKPoints3"

#####???????????????#########################################
# eDensity parameters
#####???????????????#########################################
Precision=$PrecisionCommon
MinEnergyeDensity=-3.0
MaxEnergyeDensity=3.0
AllSeparated=1
ALGO=$ALGOCommon
LELF=.FALSE.
CMDeDensity="$CMD --Action=ModifyFiles --Function=eDensity $CommonParameters $AdditionalParameters \
		  --Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
		  --Param:ISMEAR=$ISMEAR --Param:SIGMA=$SIGMA \
		  --Param:ALGO=$ALGO --Param:LELF=$LELF\
		  --AllSeparated=$AllSeparated \
		  --MinEnergy=$MinEnergyeDensity --MaxEnergy=$MaxEnergyeDensity \
		  --FromScratch=$eDensityFromScratch"

#####???????????????#########################################
# Phonopy parameters
#####???????????????#########################################
InterfacePhonopy=VASP
#InterfacePhonopy=VASPDFPT
nSupercell="2 2 2"
MeshPoints="8 8 8"
BandPoints=51
#NonAnalyticalTermCorrection=No
NonAnalyticalTermCorrection=Yes
#fConversion=521.471
fConversion=
# phonopy irreducible representations analysis
#   the coordinate of the k point and torelance for frequency
IRREPS="0 0 0 5e-3"


PrecisionPhonopy=$PrecisionCommon
ENCUTPhonopy=500
KeepSymmetryPhonopy=$KeepSymmetry
aKProductPhonopy=$aKProductCommon
GammaOnlyPhonopy=$GammaOnlyCommon
ISMEARPhonopy=$ISMEARCommon
SIGMAPhonopy=$SIGMACommon

#####???????????????#########################################
# Phonon / Born effective charge / dielectric tensor parameters
#####???????????????#########################################
Precision=$PrecisionCommon
ADDGRID=.TRUE.
NWRITE=3
# IBRION=5/7 are recommended, but 6/8 may work
IBRIONPhonon=8
NSW=1
LEPSILON=.TRUE.
# ISYM=0 for IR
KeepSymmetryPhonon=1
#aKProduct=fix:8/2,8/2,6/3
aKProduct=$aKProductCommon
GammaOnly=$GammaOnlyCommon
ISMEARPhonon=$ISMEARCommon
#ISMEARPhonon=-5
SIGMAPhonon=$SIGMACommon
#SIGMAPhonon=0.1
ALGO=$ALGOCommon
CalOpticsPhonon=0
CSHIFTPhonon=0.1
# Obsolete: CalVibrationPhonon sets IBRION=8
#CalVibrationPhonon=0
LRPAPhonon=.FALSE.
LELF=.FALSE.
CMDPHONON="$CMD --Action=ModifyFiles --Function=phonon $CommonParameters \
		--Precision=$Precision --Param:EDIFF=$EDIFF \
		--Param:ADDGRID=$ADDGRID \
		--Param:NWRITE=$NWRITE --Param:NSW=$NSW \
		--KeepSymmetry=$KeepSymmetryPhonon \
		--Param:ISMEAR=$ISMEARPhonon --Param:SIGMA=$SIGMAPhonon \
		--Param:ALGO=$ALGO --Param:LELF=$LELF \
		--GammaOnly=$GammaOnly --aKProduct=$aKProduct \
		--Pram::LEPSILON=$LEPSILON --IBRION=$IBRIONPhonon \
		--CalOptics=$CalOpticsPhonon --CSHIFT=$CSHIFTPhonon \
		--LRPA=$LRPAPhonon \
		--Param:LEFLF=$LELF --FromScratch=$PhononFromScratch \
		$AdditionalParameters"
#		--CalVibration=$CalVibrationPhonon \

#####???????????????#########################################
# Raman parameters
#####???????????????#########################################
export VASP_RAMAN_RUN=$VASPRaman
#export VASP_RAMAN_RUN="$VASPRaman \&> raman-job.out.txt"
#RamanModes="1 2 3"
RamanModes="2 5"
#RamanModes=`seq 1 21`
#FirstMode=01
#RamanLastMode=21
# Scheme for finite difference. Currently only 2 is supported
RamannDeriv=2
RamanStepSize=0.01

#PrecisionRaman=Normal
PrecisionRaman=$PrecisionCommon
#EDIFFRaman=$EDIFFCommon
#EDIFFRaman=1.0e-4
EDIFFRaman=1.0e-4
# IBRIONRaman=5/7 are recommended, but 6/8 may work
IBRIONRaman=8
NSWRaman=1
LEPSILONRaman=.TRUE.
NWRITERaman=3
# ISYM=0 for IR
KeepSymmetryRaman=1
#aKProduct=fix:8/2,8/2,6/3
aKProduct=$aKProductCommon
GammaOnly=$GammaOnlyCommon
ISMEARRaman=$ISMEARCommon
#ISMEARRaman=-5
SIGMARaman=$SIGMACommon
#SIGMARaman=0.1
ALGO=$ALGOCommon
CMDRaman="$CMD --Action=ModifyFiles --Function=phonon $CommonParameters \
		--Precision=$PrecisionRaman --Param:EDIFF=$EDIFFRaman \
		--Param:NWRITE=$NWRITERaman --Param:NSW=$NSWRaman \
		--KeepSymmetry=$KeepSymmetryRaman \
		--Param:ISMEAR=$ISMEARRaman --Param:SIGMA=$SIGMARaman \
		--Param:ALGO=$ALGO \
		--GammaOnly=$GammaOnly --aKProduct=$aKProduct \
		--Pram::LEPSILON=$LEPSILONRaman --IBRION=$IBRIONRaman \
		--FromScratch=$PhononFromScratch \
		$AdditionalParameters"

#############################################################################
#############################################################################
# No need to edit below
#############################################################################
#############################################################################

#============================
# Functions
#============================
function SendMail
{
	local EMail=$1
	local SMTPServer=$2
	local MailerName=$3
	local Domain=$4
	local From=$5
	local Title=$6
	local Subject=$7

	if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
		echo ' '
		echo '================================================================'
		echo "  Send notification e-mail to [$EMail]"
		echo '================================================================'
		perl $TkPerlDir/Mail/SendMail.pl --SMTPServer=$SMTPServer \
						 --MailerName=$MailerName --Domain=$Domain \
						 --WorkDir=`pwd` --HostName="$HostName" \
						 --To=$EMail --From=$From \
						 --Title=$Title --Subject="$Subject"
	fi
}

function PrintError()
{
	local Message1=$1
	local Message2=$2
	local DoExit=$3
	
	echo " "
	echo "Error: $Message1"
	echo $Message2

	if [ "$DoExit" = "1" ]; then
	  echo Stop.
	  exit
	fi
	
	return $DoExit
}

#====================================
# Set command line parameters
#====================================
echo ' '
echo '================================================================'
echo '  Change parameters from command line arguments'
echo '================================================================'
while [ $# -gt 0 ]
do
  ARG=$1
  Val=${ARG#*=}
  Key=${ARG%%=*}
  shift
  echo Change parameter $Key to $Val
  eval `echo $Key=$Val`
done

#====================================
# Show help
#====================================
if [ "$Action" = "help" ]; then
	echo DoVASP.sh [init|super|help]
	echo
	exit
fi

#====================================
# Make CIF
#====================================
if [ "$Action" = "init" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make Input Files from CIF [$CIFFile]"
	echo '================================================================'
	if [ "$CIFFile" = "auto" -o -f $CIFFile ]; then
		echo
	else
		echo Error: [$CIFFile] does not exist.
		exit
	fi
	echo run [$CMDMakeCIF]
	$CMDMakeCIF

	exit;
fi

if [ "$Action" = "super" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make Supercell from CIF [$CIFFile]"
	echo '================================================================'
	cmd="$VASPDir/MakeStructureModel.pl --Action=shift --Shift=0,0,0 --OutputFile=supercell${Arg2}x${Arg3}x${Arg4}.cif $Arg1:$Arg2,$Arg3,$Arg4"
	echo run [$cmd]
	if [ "$Arg4" = "" ]; then
		echo usage: DoVASP.sh super CIF_FileName nx ny nz
		exit
	fi

	$cmd

	exit;
fi

if [ "$MakeFilesFromCIF" = "1" -a "$CMDMakeCIF" != "" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make Input Files from CIF [$CIFFile]"
	echo '================================================================'
	if [ "$CIFFile" = "auto" -o -f $CIFFile ]; then
		echo
	else
		echo Error: [$CIFFile] does not exist.
		exit
	fi
	echo run [$CMDMakeCIF]
	$CMDMakeCIF
fi

if [ "$StopAfter" = "MakeFilesFromCIF" ]; then
	exit;
fi

#====================================
# Send EMail
#====================================
SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
	 "$Title" "$HostName: $Title started"

#====================================
# Remove atom
#====================================
if [ -n "$RemoveAtom" -a "$CMDRemoveAtom" != "" ]; then
	echo ' '
	echo '================================================================'
	echo "  Remove the Atom [$RemoveAtom]: [$CMDRemoveAtom]"
	echo '================================================================'
	cp POSCAR POSCAR.stoichiometry.$RemoveAtom > /dev/null
	$CMDRemoveAtom
fi

#====================================
# Backup to Original directory
#====================================
if [ "$BackUpOriginal" = "1" ]; then
	BackupDir=Original
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  Backup original files to ./$BackupDir"
		echo '================================================================'
		mkdir $BackupDir
		cp {*.sh,hosts,INCAR,KPOINTS,POSCAR,POTCAR,*.klist} $BackupDir > /dev/null
		cp {*.cif,*.CIF,*.pl,POSCAR.stoc*,*.ini} $BackupDir > /dev/null
	fi
fi

#====================================
# MD
#====================================
if [ "$DoMD" = "1" -a  "$CMDMD" != "" ]; then
	BackupDir=MD
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  MD run: [$CMDMD]"
		echo '================================================================'
		$CMDMD
		$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
		cp INCAR INCAR.prev
		cp INCAR.RWIGS INCAR

		rm *.txt > /dev/null
		$VASP | $TEE `hostname`.out.txt

#		$MXDFileConv --Action=VASPConvCONTCAR --DBDir=$(HOME)/bin/rietan --CalcRDF=0 --CoordinationNumber=4 $ARG1
#		$MXDFileConv --Action=VASPMakeXSF     --DBDir=$(HOME)/bin/rietan --CalcRDF=0 --CoordinationNumber=4 $ARGDIR/OUTCAR
		$MakeCIFCMD .
		$MakeXSFCMD .

#		$CMD --Action=MakeCIF . initial.cif
		cp POSCAR POSCAR.prev > /dev/null
		cp POSCAR POSCAR.initial > /dev/null
		cp CONTCAR POSCAR > /dev/null
#		$CMD --Action=MakeCIF . final.cif

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,POSCAR.initial,OUTCAR,IBZKPT,EIGENVAL,DOSCAR,CONTCAR} $BackupDir > /dev/null
		cp {*.txt,*.cif,*.xsf,DOS*.csv,*.xml,*.html} $BackupDir > /dev/null

#		perl $VASPScriptDir/MakeSummaryHTML.pl
#		RETCODE=$?
#		if [ $RETCODE -ne  0 -a $RETCODE -ne  3 ]; then
#			echo ' '
#			echo "Error: MD terminated incorrectly with return code [$RETCODE]."
#			exit
#		fi
		cp *.html $BackupDir > /dev/null
		rm *.cif *.xsf *.html > /dev/null
	fi
fi

if [ "$StopAfter" = "MD" ]; then
	exit;
fi

#====================================
# VCRelax Rough
#====================================
if [ "$DoVCRelaxRough" = "1"  -a "$CMDVCRelaxRough" != "" ]; then
	BackupDir=VCRelax1
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  VCRelaxRough run: [$CMDVCRelaxRough]"
		echo '================================================================'

		rm *.cif *.struct.* *.struct *.xsf *.txt > /dev/null
		$CMDVCRelaxRough
		$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
		cp INCAR INCAR.prev
		cp INCAR.RWIGS INCAR

		cp POSCAR POSCAR.initial > /dev/null

		$VASP | $TEE `hostname`.out.txt

#		$MXDFileConv --Action=VASPConvCONTCAR --DBDir=$(HOME)/bin/rietan --CalcRDF=0 --CoordinationNumber=4 $ARG1
#		$MXDFileConv --Action=VASPMakeXSF     --DBDir=$(HOME)/bin/rietan --CalcRDF=0 --CoordinationNumber=4 $ARGDIR/OUTCAR
		$MakeCIFCMD .
		$MakeSymmetrizedCIFCMD
		$MakeXSFCMD .
		phonopy --symmetry | $TEE Symmetry.txt

#		$CMD --Action=MakeCIF . initial.cif
		cp POSCAR POSCAR.prev > /dev/null
		cp CONTCAR POSCAR > /dev/null
#		$CMD --Action=MakeCIF . final.cif

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,POSCAR.initial,OUTCAR,IBZKPT,EIGENVAL,DOSCAR,CONTCAR} $BackupDir > /dev/null
		cp {OSZICAR,PCDAT,XDATCAR,PROCAR} > /dev/null
		cp {*.struct,*.struct.out,*.txt,*.cif,*.xsf,DOS*.csv,*.xml,*.html} $BackupDir > /dev/null

		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
		if [ $RETCODE -ne  0 ]; then
#		if [ $RETCODE -ne  0 -a $RETCODE -ne  3 ]; then
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP VCRelaxRough"
			PrintError "VCRelaxRough terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP VCRelaxRough. Continue." 0
		fi
		cp *.html $BackupDir > /dev/null
		rm *.cif *.xsf *.html > /dev/null
	fi
fi

if [ "$StopAfter" = "VCRelaxRough" ]; then
	exit;
fi

#====================================
# VCRelax
#====================================
if [ "$DoVCRelax" = "1" ]; then
	BackupDir=VCRelax
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  VCRelax run: [$CMDVCRelax]"
		echo '================================================================'

		rm *.cif *.initial *.struct.* *.struct *.xsf *.txt > /dev/null
		$CMDVCRelax
		$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
		cp INCAR INCAR.prev
		cp INCAR.RWIGS INCAR

		cp POSCAR POSCAR.initial > /dev/null

		$VASP | $TEE `hostname`.out.txt

		$MakeCIFCMD .

		$MakeSymmetrizedCIFCMD
		$MakeXSFCMD .
		phonopy --symmetry | $TEE Symmetry.txt

#		$CMD --Action=MakeCIF . initial.cif
		cp POSCAR POSCAR.prev > /dev/null
		cp CONTCAR POSCAR > /dev/null
#		$CMD --Action=MakeCIF . final.cif

		$CMD --Action=MakeDOSCSV --Width=$DOSWidth --IgnoreZero=0 DOSCAR DOS-up.csv DOS-dn.csv

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,POSCAR.initial,OUTCAR} $BackupDir > /dev/null
		cp {IBZKPT,EIGENVAL,DOSCAR,CONTCAR} $BackupDir > /dev/null
		cp {OSZICAR,PCDAT,XDATCAR,PROCAR} > /dev/null
		cp {*.struct,*.struct.out,*.txt,*.cif,*.xsf,DOS*.csv,*.xml,*.html} $BackupDir > /dev/null

		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
		if [ $RETCODE -ne  0 ]; then
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP VCRelax"
			PrintError "VCRelax terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP VCRelax. Terminate" 1
		fi
		cp *.html $BackupDir > /dev/null
		rm *.cif *.xsf *.html > /dev/null
	fi
fi

if [ "$StopAfter" = "VCRelax" ]; then
	exit;
fi

#====================================
# Change NBANDS
#====================================
if [ "$ChangeNBANDS" = "1" -a "$NBANDS" != "" -a "$CMDChangeNBANDS" != "" ]; then
	echo ' '
	echo '================================================================'
	echo "  Change NBANDS run for NBANDS=[$NBANDS]: [$CMDChangeNBANDS]"
	echo '================================================================'
	$CMDChangeNBANDS
fi

#====================================
# Change NELECT
#====================================
if [ "$ChangeNELECT" = "1" -a "$NELECT" != "" -a "$CMDChangeNELECT" != "" ]; then
	echo ' '
	echo '================================================================'
	echo "  Change NELECT run for NBANDS=[$NELECT]: [$CMDChangeNELECT]"
	echo '================================================================'
	$CMDChangeNELECT
fi

#====================================
# DFTSCF
#====================================
if [ "$DoDFTSCF" = "1" ]; then
	BackupDir=DFTSCF
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  DFTSCF run: [$CMDDFTSCF]"
		echo '================================================================'
		$CMDDFTSCF
		$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
		cp INCAR INCAR.prev
		cp INCAR.RWIGS INCAR

		rm *.txt *.csv *.xsf > /dev/null

		$VASP | $TEE `hostname`.out.txt
		$CMD --Action=MakeDOSCSV --Width=$DOSWidth --IgnoreZero=0 DOSCAR DOS-up.csv DOS-dn.csv

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,OUTCAR,IBZKPT,EIGENVAL,DOSCAR,WAVECAR,CHG,CHGCAR} $BackupDir > /dev/null
		cp {AEC*,LOCPOT,OSZICAR,PCDAT,XDATCAR,PROCAR,REPORT} > /dev/null
		cp {*.txt,Optics.csv,DOS*.csv,*.xsf,*.xml,*.html} $BackupDir > /dev/null

		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
		if [ $RETCODE -ne  0 ]; then
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP DFTSCF"
			PrintError "DFTSCF terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP DFTSCF. Terminate." 1
		fi
		cp *.html $BackupDir > /dev/null
		rm Optics.csv Vibration.txt DOS*.csv *.xsf *.html > /dev/null
	fi
fi

if [ "$StopAfter" = "DFTSCF" ]; then
	exit;
fi

#====================================
# SCF
#====================================
if [ "$DoSCF" = "1" ]; then
	BackupDir=SCF
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  SCF run: [$CMDSCF]"
		echo '================================================================'
		$CMDSCF
		$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
		cp INCAR INCAR.prev
		cp INCAR.RWIGS INCAR

		rm *.txt *.csv *.xsf > /dev/null

		$VASP | $TEE `hostname`.out.txt
		$CMD --Action=MakeDOSCSV --Width=$DOSWidth --IgnoreZero=0 DOSCAR DOS-up.csv DOS-dn.csv

		if [ "$CalVibrationSCF" == "1" -o "$CalOpticsSCF" == "1" ]; then
			perl $VASPScriptDir/SummarizeProperties.pl OUTCAR Optics.csv Vibration.txt Vibration.xsf
		fi

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,OUTCAR,IBZKPT,EIGENVAL,DOSCAR,WAVECAR,CHG,CHGCAR} $BackupDir > /dev/null
		cp {AEC*,LOCPOT,OSZICAR,PCDAT,XDATCAR,PROCAR,REPORT} > /dev/null
		cp {*.txt,Optics.csv,DOS*.csv,*.xsf,*.xml,*.html} $BackupDir > /dev/null

		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
		if [ $RETCODE -ne  0 ]; then
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP SCF"
			PrintError "SCF terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP SCF. Terminate." 1
		fi
		cp *.html $BackupDir > /dev/null
		rm Optics.csv Vibration.txt DOS*.csv *.xsf *.html > /dev/null
	fi
fi

if [ "$StopAfter" = "SCF" ]; then
	exit;
fi

#====================================
# DOS
#====================================
cd $BaseDir

if [ "$CalculateDOS" = "1" -a "$CMDDOS" != "" ]; then
	BackupDir=DOS
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rmdir -rif $BackupDir
		mkdir $BackupDir
		cd $BackupDir

		echo ' '
		echo '================================================================'
		echo "  DOS run: [$CMDDOS]"
		echo '================================================================'

		cp $BaseDir/{hosts,*.ini} .
		cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS,WAV*,CHG*} .
		$CMDDOS .
		$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
		cp INCAR INCAR.prev
		cp INCAR.RWIGS INCAR

		MKL_NUM_THREADS=$nCPUForMKLDOS
		$VASPDOS | $TEE `hostname`.out.txt
		MKL_NUM_THREADS=$nCPUForMKL
		$CMD --Action=MakeDOSCSV --Width=$DOSWidth --IgnoreZero=0 DOSCAR DOS-up.csv DOS-dn.csv

		if [ "$CalVibrationDOS" == "1" -o "$CalOpticsDOS" == "1" ]; then
			perl $VASPScriptDir/SummarizeProperties.pl OUTCAR Optics.csv Vibration.txt Vibration.xsf
		fi

		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
		if [ $RETCODE -ne  0 ]; then
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP DOS"
			PrintError "DOS terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP DOS. Continue." 0
		fi

		rm WAV* CHG* *.dos *.prev
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "DOS" ]; then
	exit;
fi

#====================================
# Band
#====================================
cd $BaseDir

if [ "$CalculateBand" = "1" ]; then
	if [ "$BandKPoints1" != "" -a "CMDBandX" != "" ]; then
		BackupDir=BandX
		if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
			echo "Dir [$BackupDir] exists."
			echo "Skip."
		else
			rmdir -rif $BackupDir
			mkdir $BackupDir
			cd $BackupDir

			echo ' '
			echo '================================================================'
			echo "  Band1 run for Band=[$Band1]: [$CMDBandX .]"
			echo '================================================================'

			cp $BaseDir/hosts .
			cp $BaseDir/*.klist .
			cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS} .
			if [ "$HybridFunctional" = "" ]; then
				cp $BaseDir/SCF/{WAV*,CHG*} .
			else 
				cp $BaseDir/DFTSCF/{WAV*,CHG*} .
			fi
			$CMDBandX .
			cp KPOINTS.band KPOINTS

			$VASP | $TEE `hostname`.out.txt

			perl $VASPScriptDir/MakeSummaryHTML.pl
			RETCODE=$?
			if [ $RETCODE -ne  0 ]; then
				SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
				     "$Title" "$HostName: $Title failed in VASP Band1"
				PrintError "Band1 terminated incorrectly with return code [$RETCODE]." \
					   "Something wrong in VASP Band1. Continue." 0
			fi
			rm WAV* CHG* *.band *.prev
		fi
	fi

	if [ "$StopAfter" = "BandX" ]; then
		exit;
	fi

	cd $BaseDir
	if [ "$BandKPoints1" != "File" -a "$BandKPoints2" != "" -a "CMDBandY" != "" ]; then
		BackupDir=BandY
		if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
			echo "Dir [$BackupDir] exists."
			echo "Skip."
		else
			rmdir -rif $BackupDir
			mkdir $BackupDir
			cd $BackupDir

			echo ' '
			echo '================================================================'
			echo "  Band1 run for Band=[$Band2]: [$CMDBandY .]"
			echo '================================================================'

			cp $BaseDir/hosts .
			cp $BaseDir/*.klist .
			cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS} .
			if [ "$HybridFunctional" = "" ]; then
				cp $BaseDir/SCF/{WAV*,CHG*} .
			else 
				cp $BaseDir/DFTSCF/{WAV*,CHG*} .
			fi
			$CMDBandY .
			cp KPOINTS.band KPOINTS

			$VASP | $TEE `hostname`.out.txt

			perl $VASPScriptDir/MakeSummaryHTML.pl
			RETCODE=$?
			if [ $RETCODE -ne  0 ]; then
				SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
				     "$Title" "$HostName: $Title failed in VASP Band2"
				PrintError "Band2 terminated incorrectly with return code [$RETCODE]." \
					   "Something wrong in VASP Band2. Continue" 0
			fi
			rm WAV* CHG* *.band *.prev
		fi
	fi

	if [ "$StopAfter" = "BandY" ]; then
		exit;
	fi

	cd $BaseDir
	if [ "$BandKPoints1" != "File" -a "$BandKPoints3" != "" -a "CMDBandZ" != "" ]; then
		BackupDir=BandZ
		if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
			echo "Dir [$BackupDir] exists."
			echo "Skip."
		else
			rmdir -rif $BackupDir
			mkdir $BackupDir
			cd $BackupDir

			echo ' '
			echo '================================================================'
			echo "  Band1 run for Band=[$Band3]: [$CMDBandZ .]"
			echo '================================================================'

			cp $BaseDir/hosts .
			cp $BaseDir/*.klist .
			cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS} .
			if [ "$HybridFunctional" = "" ]; then
				cp $BaseDir/SCF/{WAV*,CHG*} .
			else 
				cp $BaseDir/DFTSCF/{WAV*,CHG*} .
			fi
			$CMDBandZ .
			cp KPOINTS.band KPOINTS

			$VASP | $TEE `hostname`.out.txt

			perl $VASPScriptDir/MakeSummaryHTML.pl
			RETCODE=$?
			if [ $RETCODE -ne  0 ]; then
				SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
				     "$Title" "$HostName: $Title failed in VASP Band3"
				PrintError "Band3 terminated incorrectly with return code [$RETCODE]." \
					   "Something wrong in VASP Band3. Continue" 0
			fi
			rm WAV* CHG* *.band *.prev

			cd $BaseDir

			echo ' '
			echo '================================================================'
			echo "  Merge Bands to BandTotal/EIGENVAL"
			echo '================================================================'
			rm EIGENVAL > /dev/null
			$CMD --Action=AddEIGENVAL --InverseOrder=No  BandX/EIGENVAL EIGENVAL
			$CMD --Action=AddEIGENVAL --InverseOrder=No  BandY/EIGENVAL EIGENVAL
			$CMD --Action=AddEIGENVAL --InverseOrder=Yes BandY/EIGENVAL EIGENVAL
			$CMD --Action=AddEIGENVAL --InverseOrder=No  BandZ/EIGENVAL EIGENVAL
			$CMD --Action=RepairEIGENVAL EIGENVAL
			BackupDir=BandTotal
			mkdir $BackupDir
			cp BandX/{INCAR,KPOINTS,POSCAR,POTCAR} $BackupDir > /dev/null
			cp {SCF/OUTCAR,EIGENVAL} $BackupDir > /dev/null
		fi
	fi

	if [ "$StopAfter" = "BandZ" ]; then
		exit;
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "Band" ]; then
	exit;
fi

#====================================
# Electron density
#====================================
cd $BaseDir

if [ "$CalculateElectronDensity" = "1" -a "$CMDeDensity" != "" ]; then
	BackupDir=$BaseDir/eDensity
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rmdir -rif $BackupDir
		mkdir $BackupDir
		cd $BackupDir
		
		echo ' '
		echo '================================================================'
		echo "  eDensity run: [$CMDeDensity $BackupDir/INCAR]"
		echo '================================================================'

#		echo "cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS,WAV*,CHG*} ."
		cp $BaseDir/hosts .
		cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS,WAV*,CHG*} .
		$CMDeDensity $BackupDir/INCAR

		$VASP | $TEE `hostname`.out.txt

		$CMD --Action=ChangeDensityFileNames --EnergyRange=3.0 --RemoveExtention=0 $BackupDir
		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
		if [ $RETCODE -ne  0 ]; then
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP eDensity"
			PrintError "eDensity terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP eDensity. Continue" 0
		fi
		
		rm WAV* CHG* *.eDensity *.prev
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "ElectronDensity" ]; then
	exit;
fi

#====================================
# Phonon
#====================================
cd $BaseDir

if [ "$CalculatePhonon" = "1" ]; then
	BackupDir=$BaseDir/Phonon
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rm -rif $BackupDir
		mkdir $BackupDir
		cd $BackupDir

		echo ' '
		echo '================================================================'
		echo "  Phonon run: [$CMDPHONON $BackupDir/INCAR]"
		echo '================================================================'

		cp $BaseDir/hosts .
		cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS,WAV*,CHG*} .
		$CMDPHONON $BackupDir/INCAR

		$VASP | $TEE `hostname`.out.txt

		$CMD --Action=MakeDOSCSV --Width=$DOSWidth --IgnoreZero=0 DOSCAR DOS-up.csv DOS-dn.csv
		if [ "$CalVibrationPhonon" == "1" -o "$CalOpticsPhonon" == "1" ]; then
			perl $VASPScriptDir/SummarizeProperties.pl OUTCAR Optics.csv Vibration.txt Vibration.xsf
		fi

		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
#		if [ $RETCODE -ne  0 ]; then
		if [ -s DYNMAT ]; then
			echo ' '
		else
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP Phonon"
			PrintError "Phonon terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP Phonon. Continue" 0
		fi

		rm WAV* CHG* *.phonon *.prev
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "Phonon" ]; then
	exit;
fi

#====================================
# Phonopy
#====================================
cd $BaseDir

if [ "$DoPhonopy" = "1" ]; then
	BackupDir=$BaseDir/Phonopy
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rm -rif $BackupDir
		mkdir $BackupDir
		cd $BackupDir

		echo ' '
		echo '================================================================'
		echo "  Phonopy run: [$DoPhonopyCMD] in `pwd`"
		echo '================================================================'

		cp $BaseDir/hosts .
		cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS,WAV*,CHG*} .
		$CMDPHONON $BackupDir/INCAR

		OriginalDirRegExp=`echo $OriginalDir | sed -e "s/\//:_:/g"`

		sed \
		    -e "s/OriginalDir={.*$/OriginalDir=\"$OriginalDirRegExp\"/" \
		    -e "s/^nCPU=.*$/nCPU=$nCPU/" \
		    -e "s/^NPAR=.*$/NPAR=$NPAR/" \
		    -e "s/^KPAR=.*$/KPAR=$KPAR/" \
		    -e "s/^nCPUForMKL=.*$/nCPUForMKL=$nCPUForMKL/" \
		    -e "s/^MKL_NUM_THREADS=.*$/MKL_NUM_THREADS=$MKL_NUM_THREADS/" \
		    -e "s/^Usebsub=.*$/Usebsub=$Usebsub/" \
		    -e "s/^Precision=.*$/Precision=$PrecisionPhonopy/" \
		    -e "s/^ENCUT=.*$/ENCUT=$ENCUTPhonopy/" \
		    -e "s/^EDIFF=.*$/EDIFF=$EDIFF/" \
		    -e "s/^EDIFFG=.*$/EDIFFG=$EDIFFG/" \
		    -e "s/^aKProduct=.*$/aKProduct=$aKProductPhonopy/" \
		    -e "s/^GammaOnly=.*$/GammaOnly=$GammaOnlyPhonopy/" \
		    -e "s/^ISMEAR=.*$/ISMEAR=$ISMEARPhonopy/" \
		    -e "s/^SIGMA=.*$/SIGMA=$SIGMAPhonopy/" \
		    -e "s/^KeepSymmetry=.*$/KeepSymmetry=$KeepSymmetryPhonopy/" \
		    -e "s/^Interface=.*$/Interface=$InterfacePhonopy/" \
		    -e "s/^nSupercell=.*$/nSupercell=\"$nSupercell\"/" \
		    -e "s/^MeshPoints=.*$/MeshPoints=\"$MeshPoints\"/" \
		    -e "s/^BandPoints=.*$/BandPoints=$BandPoints/" \
		    -e "s/^fConversion=.*$/fConversion=$fConversion/" \
		    -e "s/^NonAnalyticalTermCorrection=.*$/NonAnalyticalTermCorrection=$NonAnalyticalTermCorrection/" \
		    -e "s/^Title=.*$/Title=$Title/" \
		    -e "s/^EMail=.*$/EMail=$EMail/" \
		    -e "s/^SMTPServer=.*$/SMTPServer=$SMTPServer/" \
		    -e "s/^Domain=.*$/Domain=$Domain/" \
		    -e "s/^MailerName=.*$/MailerName=$MailerName/" \
		    -e "s/^From=.*$/From=$From/" \
		    -e "s/^DoSendMail=.*$/DoSendMail=$DoSendMail/" \
		    -e "s/^DoPhonopyDOS=.*$/DoPhonopyDOS=$DoPhonopyDOS/" \
		    -e "s/^DoPhonopyThermalProperties=.*$/DoPhonopyThermalProperties=$DoPhonopyThermalProperties/" \
		    -e "s/^DoPhonopyPDOS=.*$/DoPhonopyPDOS=$DoPhonopyPDOS/" \
		    -e "s/^DoPhonopyBand=.*$/DoPhonopyBand=$DoPhonopyBand/" \
		    $DoPhonopyTemplatePath > $DoPhonopyCMD
		chmod +x $DoPhonopyCMD

		if [ "$Usebsub" = "1" ]; then
			echo " "
			echo "Usebsub flag is set."
			echo "  When this script will be finished, "
			echo "  then copy $BackupDir/* to this directory"
			echo "  and run [$DoPhonopyCMD]."
		else
			echo "Run [$DoPhonopyCMD]."
			$DoPhonopyCMD
		fi

		echo "IRREPS = $IRREPS" > irreps.cfg
		echo "SHOW_IRREPS = .TRUE." >> irreps.cfg
		phonopy --dim="$nSupercell" irreps.cfg | $TEE irreps.txt

		
		perl $VASPScriptDir/MakeSummaryHTML.pl
		RETCODE=$?
#		if [ $RETCODE -ne  0 ]; then
		if [ -s band_NoAnalyticalTerm.yaml ]; then
			echo ' '
		else
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in Phonopy"
			PrintError "Phonopy terminated incorrectly with return code [$RETCODE]." \
				   "Something wrong in VASP Phonon. Continue" 0
		fi

		rm WAV* CHG* *.phonon *.prev
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "Phonopy" ]; then
	exit;
fi

#====================================
# IR
#====================================
cd $BaseDir

if [ "$CalculateIR" = "1" ]; then
	BackupDir=$BaseDir/IR
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rm -rif $BackupDir
		echo "mkdir $BackupDir"
		mkdir $BackupDir

		echo ' '
		echo '================================================================'
		echo "  IR run [$CalIRCMD]"
		echo '================================================================'

		cd $BackupDir
		cp $OriginalDir/Phonon/{INCAR,POTCAR,POSCAR,KPOINTS,OUTCAR} .
		cp $OriginalDir/hosts .
		$CMDIR

		$CalIRCMD

		if [ -d intensities/results ]; then
			echo ' '
		else
			SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
			     "$Title" "$HostName: $Title failed in VASP VCRelaxRough"
			PrintError "[intensities/results] does not exist." \
				   "Something wrong in IR. Continue." 0
		fi

		rm WAV* CHG* *.prev
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "IR" ]; then
	exit;
fi

#====================================
# Raman
#====================================
cd $BaseDir

if [ "$CalculateRaman" = "1" ]; then
	BackupDir=$BaseDir/Raman
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rm -rif $BackupDir
		mkdir $BackupDir
		cd $BackupDir

		echo ' '
		echo '================================================================'
		echo "  Raman run: [python $CalRamanCMD]"
		echo '================================================================'
#echo [$RamanModes]

		cp $OriginalDir/Phonon/{INCAR,POSCAR,POTCAR,KPOINTS} .
		cp $OriginalDir/hosts .
		echo "[$CMDRaman $BackupDir/INCAR]"
		$CMDRaman $BackupDir/INCAR
		cp POSCAR POSCAR.phon
		cp $OriginalDir/Phonon/OUTCAR OUTCAR.phon
		for i in $RamanModes
		do

			export VASP_RAMAN_PARAMS="${i}_${i}_${RamannDeriv}_${RamanStepSize}"
			echo "  Run[$CalRamanCMD] with VASP_RAMAN_PARAMS=$VASP_RAMAN_PARAMS]"
			python $CalRamanCMD --gen

			mv POSCAR.-1.out POSCAR.-1.${i}
			rm *.prev *.phonon
		done
		cp POSCAR.phon POSCAR

		for i in $RamanModes
		do
			if [ -f $BackupDir/POSCAR.-1.${i} ]; then
				WorkDir=$BackupDir/$i
				if [ "$SkipIfDirectoryExists" = "1" -a -d $WorkDir ]; then
					echo "Dir [$WorkDir] exists."
					echo "Skip."
				else
					rmdir -rif $WorkDir
					mkdir $WorkDir
					cd $WorkDir
					echo "   Run in [$WorkDir]"

					cp $OriginalDir/Phonon/{INCAR,POSCAR,POTCAR,KPOINTS} .
					cp $OriginalDir/hosts .
					echo "[$CMDRaman $WorkDir/INCAR]"
					$CMDRaman $WorkDir/INCAR
					cp POSCAR POSCAR.phon
					cp $OriginalDir/Phonon/OUTCAR OUTCAR.phon

					export VASP_RAMAN_PARAMS="${i}_${i}_${RamannDeriv}_${RamanStepSize}"
					echo "  Run[$CalRamanCMD] with VASP_RAMAN_PARAMS=$VASP_RAMAN_PARAMS]"
					python $CalRamanCMD | $TEE `hostname`-vasp_raman.out.txt

					if [ -s vasp_raman.dat ]; then
						echo ' '
					else
						SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
						     "$Title" "$HostName: $Title failed in VASP VCRelaxRough"
						PrintError "[vasp_raman.dat] does not exist." \
						 	  "Something wrong in Raman. Continue." 0
					fi

					rm WAV* CHG* *.prev *.phonon *.prev
				fi
			fi
		done
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "Raman" ]; then
	exit;
fi

#====================================
# Clean up files
#====================================
cd $BaseDir

#rm -rif intensities
if [ "$DeleteExtraFiles" = "1" ]; then
	echo ' '
	echo '================================================================'
	echo "  Clean up files"
	echo '================================================================'
	rm *.prev *.vc-* *.relax *.scf *.dos *.band *.eDensity *.phon* *.init* *.remove* *.stoichi* > /dev/null
	rm {vasprun.xml,EIGENVAL,ELFCAR,LOCPOT,DYNMAT,REPORT,AECCAR*,vasp_raman*} > /dev/null
	rm {CONTCAR,DOSCAR,OUTCAR} > /dev/null
	rm {OSZICAR,PCDAT,XDATCAR,PROCAR,WAVE*,CHG*} > /dev/null
	rm {DOS-*.csv,*.out,*.struct} > /dev/null
	rm {*.txt,IBZ*} > /dev/null
	rm *.conf *.yaml *.pdf *.dat FORCE* POSCAR-* SPOSCAR
	rm Band*/DOS* > /dev/null
#	rm SCF/DOS* > /dev/null
	rm VCRelax/DOS* > /dev/null
	rm VCRelax1/DOS* > /dev/null
fi
if [ "$DeleteLargeFiles" = "1" ]; then
	echo ' '
	echo '================================================================'
	echo "  Delete large fils (WAVCAR,CHG,CHGCAR)"
	echo '================================================================'
	rm SCF/{WAVE*,CHG*} > /dev/null
fi

#====================================
# Make Summary
#====================================
if [ "$MakeSummary" = "1" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make summary to Summarize.txt and Summarize-SpinPolarized.txt"
	echo '================================================================'
	perl $VASPScriptDir/Summarize2.pl ./ > Summarize.txt
	perl $VASPScriptDir/Summarize.pl  ./ > Summarize-SpinPolarized.txt
	perl $VASPScriptDir/MakeSummaryHTML.pl
fi

#====================================
# Send EMail
#====================================
SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
	 "$Title" "$HostName: $Title completed"
