#!/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`
export nCPU=`grep -c '^processor' /proc/cpuinfo`

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

#####???????????????#########################################
# Parallelization configurations: Edit for your PC
#####???????????????#########################################
#******** IMPORTANT *********
if [[ "$HostName" = "usrv1" ]]; then
  nCPU=12
  NPAR=4
elif [[ "$HostName" = "csrv11" || "$HostName" = "csrv12" || "$HostName" = "csrv13" || "$HostName" = "csrv14" ]]; then
  nCPU=16
  NPAR=4
elif [[ "$HostName" = "csrv9" || "$HostName" = "csrv10" ]]; then
  nCPU=16
  NPAR=4
elif [[ "$HostName" = "csrv7" || "$HostName" = "csrv8" ]]; then
  nCPU=16
  NPAR=4
else
  nCPU=16
  NPAR=4
fi
#KPAR=4
nCPUForMKL=1
#nCPUForMKLDOS=$nCPU
nCPUForMKLDOS=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
if [ "$HostName" = "usrv2.r3-3.lan" ]; then
#  MPIBIN=/opt/intel/oneapi/compiler/2023.1.0/linux/bin
#  MPIBIN=/opt/intel/compilers_and_libraries_2017.2.174/linux/mpi/intel64/bin
#  MPICMD="mpirun"
  VASPPATH=vasp_std
  VASPNCLPATH=vasp_ncl
elif [ "$HostName" = "csrv7" -o "$HostName" = "csrv8" ]; then
  VASPPATH=vasp_std
  VASPNCLPATH=vasp_ncl
else
  VASPPATH=vasp_std
  VASPNCLPATH=vasp_ncl
fi

VASP="mpirun -n $nCPU $VASPPATH"
VASPDOS="mpirun -n $nCPU $VASPPATH"
#VASPDOS="$VASPPATH"
Usebsub=0
# VASPPhonopy is defined n DoPhonopyTemplate
VASPRaman=$VASP

PerlPATH=/usr/bin/perl
PythonPATH=python
Python2PATH=python2

VASPKITPATH=vaspkit

BoltzTraPPATH=btp2
MSScriptDIR=$tkprog_X_path/VASP/minamishima

LDDir=$MYAPPDIR/LD
RamanSCDir=$MYAPPDIR/raman-sc
BaderCMD="$tkProg_Root/bin/bader"
EnergyPath=$tkProg_Root/bin/energy

VASPDir=$tkprog_X_path/VASP
VASPScriptDir=$VASPDir/script

export "CMD=$PerlPATH $VASPDir/VASP.pl"
VASPFSCMD="$PerlPATH $VASPDir/VASPFS.pl"
VASPLDCMD="$PerlPATH $VASPDir/VASPLD.pl"
export "PHONOPYplCMD=$PerlPATH $VASPDir/Phonopy.pl"
export "WIEN2kplCMD=$PerlPATH $TkPerlDir/WIEN2k/WIEN2k.pl"

MakeCIFCMD="$CMD --Action=ConvCONTCARFiles"
MakeXSFCMD="$CMD --Action=MakeRelaxXSFFile --kMagnetization=0.8 --ArrowColor=255:0:0 --ArrowRadius=0.2"
#MakeSymmetrizedCIFCMD="$WIEN2kplCMD --Action=MakeSymmetrizedStructFile --TOL=0.001 *-final.cif out.struct"
MakeSymmetrizedCIFCMD="python $tkprog_X_path/crystal/symmetrize_pymatgen.py *-final.cif symmetrized.cif"

CalIRCMD=$VASPScriptDir/CalIR.sh
CalRamanCMD=$RamanSCDir/vasp_raman.py
#DoPhonopyTemplatePath=$VASPScriptDir/DoPhonopy.sh
DoPhonopyTemplatePath=$VASPScriptDir/DoPhonopy-Template20180418.sh
DoPhonopyCMD=DoPhonopy.sh

# Utitlities
TEE=tee

#====================================================
# 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.

# Obsolete parameters, not used
#For MakeCIF: 
##DefaultFunction=scf # Obsolete, not used
##NKRED=2
##ISMEARHybridFunctional=1
##SIGMAHybridFunctionl=0.2
#Obsolete. Use AdditionalParameters=--NBANDS=x2 option
ChangeNBANDS=0
ChangeNELECT=0

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

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

MakeFilesFromCIF=1 
CIFFile=auto
#SpinPolarized={SpinPolarized}
SpinPolarized=No 
  #SpinPolarized=Yes

#UseConventionalCell={UseConventionalCell}
UseConventionalCell=No 
  #UseConventionalCell=Yes

#DFT Functional=PAW_LDA64|PAW_PBE64|PAW_LDA54|PAW_PBE54
#GGA: PE: PBE RE: revPBE RP: RPBE PS: PBEsol AM: AM05
#     B3: B3LYP with VWN3  B5: B3LYP with VWN5
#HybridFunctional=HF|HSE|PBE0
Functional=PAW_PBE64 
GGA=PS    #PBEsol 
HybridFunctional= 

LASPH=.FALSE. 
ADDGRID=.FALSE.
IMIX=4
NELM=100

#Meta GGA: TPSS|RTPSS|M06L|MBJ|LMBJ
METAGGA= 
  if [[ "$METAGGA" != "" ]]; then
    FunctionalForMBJ=PAW_LDA64
    LASPH=.TRUE.
    #CMBJ="1.5,1.5"
    IMIX=1
    ADDGRID=.TRUE.
    NELM=100
  fi

#Choose POTCAR if needed
  #UseRecommendedPOTCAR=Ba=Ba_sv,Si=Si,O=O_h
#BurstPOTCAR: 0 => Use same POTCAR for the same atom types; Site => Burst POTCAR for independent atom sites
BurstPOTCAR=0

SpinOrbit=.FALSE. 
  #SpinOrbit=.TRUE.
  #NonCollinear=
NoSOCForIonDynamics=1

LMAXMIX=6
LMAXMIXForSO=6

# set .TRUE. if you use KPOINTS_OPT for HF calculations
LKPOINTS_OPT=.FALSE.

MakeCIFParams=
# Spcify the volume percentages of WS spheres if update RWIGS in INCAR
UseDBRWIGs=1
UpdateRWIGsByRBader=0.9 

BackUpOriginal=1

DoMD=0 
DoVCRelaxRough=1 
DoVCRelax=1 
# For hybrid calculations perform DFTSCF anyway
# For DFT DFTSCF is equal to SCF, should be DoDFTSCF=0
DoDFTSCF=0 
if [ "$HybridFunctional" = "" ]; then
	DoDFTSCF=0
fi
DoSCF=0 
CalLDEnergyForSCF=1

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

CalculateBand=0
# specify 'vaspkit' to generate band KPOINTS by VASPKIT, 'File' to use pre-existing file
BandKPoints1Common=vaspkit 
  #BandKPoints1Common=vaspkit
  #BandKPoints1Common=File
  #BandKPoints1Common=XG

CalculateEffectiveMass=0

CalculateElectronDensity=0 

CalculateFermiSurface=0

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

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

CalculateIR=0 
CalculateRaman=0 

CalculateBoltzTraP=0 
BoltzTrap_emin=-0.5
BoltzTrap_emax=0.5
BoltzTrap_ninterp=20
BoltzTrap_T=300
BoltzTrap_ebin=3001

MakeSummary=1
DeleteExtraFiles=0 
DeleteLargeFiles=0 

#####???????????????#########################################
# SCF continuation switches: Usually no need to edit
#####???????????????#########################################
MDFromScratch=1
VCRelaxRoughFromScratch=0
VCRelaxFromScratch=0
DFTSCFFromScratch=1
SCFFromScratch=1
DOSFromScratch=0
eDensityFromScratch=0
FSFromScratch=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=.FALSE. --ENCUT=520'
#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=Accurate 
#PrecisionCommon=High
#aKProductCommon=2.5
aKProductCommon=2.0 
#aKProductCommon=fix:3,3,3
#aKProductCommon=fix:8/2,8/2,6/3
GammaOnlyCommon=0 
#ISMEARCommon=0
ISMEARCommon=0 
SIGMACommon=0.001 
#SIGMACommon=0.01

# For others: Normal or Fast would be recommended
#ALGOCommon=All
#ALGOCommon=Diag
#ALGOCommon=38
ALGOCommon=Normal
# For hybrid: All, Diag, or Damped
HybridALGO=Diag

#====================================================
# MakeCIF command
#====================================================
SpinOrbitForIonDynamics=.FALSE.
if [ "$SpinOrbit" = ".TRUE." -a "$NoSOCForIonDynamics" != "1" ]; then
  $SpinOrbitForIonDynamics=.TRUE.
  VASP="$MPIBIN/mpirun -machinefile hosts -np $nCPU $VASPNCLPATH"
  VASPDOS="$MPIBIN/mpirun -machinefile hosts -np 1 $VASPNCLPATH"
  VASPRaman=$VASP
  if [ "$LMAXMIXForSO" != "" ]; then
    LMAXMIX=$LMAXMIXForSO
  fi

  echo Parameters modified for spin-orbit coupling
  echo "  Use SOC: $SpinOrbitForIonDynamics"
  echo "  LMAXMIX=$LMAXMIX"
  echo "  VASP=$VASP"
  echo "  VASPDOS=$VASPDOS"
  echo "  VASPRaman=$VASPRaman"
fi

MakeCIFOption="--UseConventionalCell=$UseConventionalCell \
	--UseRecommendedPOTCAR=$UseRecommendedPOTCAR --Function=scf \
	--HybridFunctional=$HybridFunctional \
	--BurstPOTCAR=$BurstPOTCAR \
	--LKPOINTS_OPT=$LKPOINTS_OPT \
	$MPIParams $MakeCIFParams $AdditionalParameters \
	--SpinOrbit=$SpinOrbitForIonDynamics --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--SpinPolarized=$SpinPolarized $CIFFile ./"
#	--NKRED=$NKRED --ISMEARHybridFunctional=$ISMEARHybridFunctional \
#	--SIGMAHybridFunctionl=$SIGMAHybridFunctionl \

CMDMakeCIF="$CMD --Action=MakeINCAR --Functional=$Functional --GGA=$GGA \
	    --METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	    $MakeCIFOption"
CMDMakeCIFForMBJ="$CMD --Action=MakeINCAR --Functional=$FunctionalForMBJ --METAGGA=$METAGGA $MakeCIFOption"

#===========================================================
# 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=Normal 
GammaOnlyMD=1 
aKProductMD=1.5 
#aKProductMD=fix:1/1,1/1,1/1
ALGO=53
ISMEARMD=0    # Gaussian smearing 
SIGMAMD=0.1 
KeepSymmetryMD=0 
NSWMD=2000 
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 \
		--SpinOrbit=$SpinOrbitForIonDynamics --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
		--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 
PrecisionVCRelaxRough=Norm 
NSWVCRelaxRough=300
KeepSymmetryRough=1 
#aKProductRough=fix:8/2,8/2,6/3
aKProductRough=1.5 
GammaOnlyVCRelaxRough=0 
ISMEARVCRelaxRough=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=$PrecisionVCRelaxRough --Param:EDIFF=$EDIFFRough --Param:EDIFFG=$EDIFFGRough \
	--SpinOrbit=$SpinOrbitForIonDynamics --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--SpinPolarized=$SpinPolarized --PStress=$PStress \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--Param:ISMEAR=$ISMEARVCRelaxRough --Param:SIGMA=$SIGMAVCRelaxRough \
	--Param:ALGO=$ALGO --Param:LELF=$LELF\
	--Param:NSW=$NSWVCRelaxRough \
	--GammaOnly=$GammaOnlyVCRelaxRough --aKProduct=$aKProductRough $AdditionalParameters \
	--KeepSymmetry=$KeepSymmetryRough --FromScratch=$VCRelaxRoughFromScratch $ARG1"

#####???????????????#########################################
# VCRelax parameters
#####???????????????#########################################
#RelaxMode=vc-relax|relax
RelaxMode=vc-relax 
NSWRelax=300 
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=$NSWRelax \
	--SpinOrbit=$SpinOrbitForIonDynamics --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--GammaOnly=$GammaOnlyVCRelax --aKProduct=$aKProductVCRelax $AdditionalParameters \
	--KeepSymmetry=$KeepSymmetry --FromScratch=$VCRelaxFromScratch $ARG1"

#####???????????????#########################################
# Spin-Orbit configrations for single-point calculations
#####???????????????#########################################
if [ "$SpinOrbit" = ".TRUE." ]; then
  VASP="$MPIBIN/mpirun -machinefile hosts -np $nCPU $VASPNCLPATH"
  VASPDOS="$MPIBIN/mpirun -machinefile hosts -np 1 $VASPNCLPATH"
  VASPRaman=$VASP
  if [ "$LMAXMIXForSO" != "" ]; then
    LMAXMIX=$LMAXMIXForSO
  fi

  echo Parameters modified for spin-orbit coupling
  echo "  Use SOC: $SpinOrbit"
  echo "  LMAXMIX=$LMAXMIX"
  echo "  VASP=$VASP"
  echo "  VASPDOS=$VASPDOS"
  echo "  VASPRaman=$VASPRaman"
fi


#####???????????????#########################################
# 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\
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--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\
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--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=2.5 
GammaOnly=$GammaOnlyCommon
DOSISMEAR=-5   # tetrahedron method with Blochl corrections 
DOSSIGMA=0.1 
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=.FALSE. 

#CMDDOS="$CMD --Action=ModifyFiles --Function=dos --Param:NPAR=$DOSNPAR --Param:LREAL=.FALSE. $CommonParameters \
CMDDOS="$CMD --Action=ModifyFiles --Function=dos --Param:NPAR=$DOSNPAR $CommonParameters \
	--Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
	--Param:ISMEAR=$DOSISMEAR --Param:SIGMA=$DOSSIGMA \
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--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=vaspkit to use VASPKIT, =File to use *.klist file
Precision=$PrecisionCommon
NELMIN=5
BANDISMEAR=1
BANDSIGMA=0.1
BandKPoints1=$BandKPoints1Common
BandKPoints2=GY
BandKPoints3=GZ
nKPoint=51
#ALGO=$ALGOCommon
if [ "$HybridFunctional" != "" ]; then
	ALGO=$HybridALGO
fi
LELF=.FALSE. 
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 \
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--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 \
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--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 \
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--Param:NELMIN=$NELMIN \
	--GammaOnly=0 --nKPoint=$nKPoint --KPoints=$BandKPoints3"

#####???????????????#########################################
# EffectiveMass parameters
#####???????????????#########################################
Precision=$PrecisionCommon
NELMIN=5
BANDISMEAR=1
BANDSIGMA=0.1
#ALGO=$ALGOCommon
if [ "$HybridFunctional" != "" ]; then
	ALGO=$HybridALGO
fi
LELF=.FALSE. 
CMDEffectiveMass="$CMD --Action=MakeKPOINTSforMass"

#####???????????????#########################################
# 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\
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--AllSeparated=$AllSeparated \
	--MinEnergy=$MinEnergyeDensity --MaxEnergy=$MaxEnergyeDensity \
	--FromScratch=$eDensityFromScratch"

#####???????????????#########################################
# Fermi surface parameters
#####???????????????#########################################
Precision=$PrecisionCommon
FSNPAR=1
UseSymmetryFS=1
EFminFS=-3.0
EFmaxFS=-3.0
aKProductFS=5.0
FSISMEAR=$ISMEARCommon
FSSIGMA=$SIGMACommon
CMDFS="$CMD --Action=ModifyFiles --Function=FS --Param:NPAR=$FSNPAR --Param:LREAL=.FALSE. $CommonParameters \
	--Precision=$Precision --Param:EDIFF=$EDIFF --Param:EDIFFG=$EDIFFG \
	--Param:ISMEAR=$FSISMEAR --Param:SIGMA=$FSSIGMA \
	--GammaOnly=0 --aKProduct=$aKProductFS \
	--Param:ALGO=$ALGO --Param:LELF=.FALSE. --Param:LVTOT=$LVTOT --Param:LVHAR=$LVHAR\
	--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
	--METAGGA=$METAGGA --CMBJ=$CMBJ --LASPH=$LASPH --IMIX=$IMIX --NELM=$NELM --ADDGRID=$ADDGRID \
	--DOSMeasreudFromEF=1 --MinEnergy=$MinEnergy --MaxEnergy=$MaxEnergy --nMesh=$nMesh \
	--CalOptics=0 --CSHIFT=$CSHIFTDOS \
	--FromScratch=$FSFromScratch \
	$AdditionalParameters"

#####???????????????#########################################
# 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
NSWPhonon=1
LEPSILON=.TRUE.
# ISYM=0 for IR
KeepSymmetryPhonon=1
#aKProduct=fix:8/2,8/2,6/3
aKProduct=2.0 
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=$NSWPhonon \
		--KeepSymmetry=$KeepSymmetryPhonon \
		--Param:ISMEAR=$ISMEARPhonon --Param:SIGMA=$SIGMAPhonon \
		--Param:ALGO=$ALGO --Param:LELF=$LELF \
		--GammaOnly=$GammaOnly --aKProduct=$aKProduct \
		--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
		--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=2.0 
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 \
		--SpinOrbit=$SpinOrbit --NonCollinear=$NonCollinear --LMAXMIX=$LMAXMIX \
		--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|scratch|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
	if [[ "$METAGGA" != "" ]]; then
		echo run [$CMDMakeCIFForMBJ]
		$CMDMakeCIFForMBJ
		mv POTCAR POTCAR.MBJ
		rm *-Primitive.cif
	fi
	echo run [$CMDMakeCIF]
	$CMDMakeCIF
	cp POTCAR POTCAR.DFT
	exit;
fi

if [ "$Action" = "scratch" ]; then
	echo ' '
	echo '================================================================'
	echo "  Restore initial files from Original and clean up"
	echo '================================================================'
	chmod -w DoVASP.sh
	rm -rif MD VCRelax* DFTSCF SCF DOS Band* Mass* eDensity Phonon* IR* Raman*
	rm *
	chmod +w DoVASP.sh
	mv Original/* .
	rm -rif Original
	rm *-Primitive.cif
	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
	if [[ "$METAGGA" != "" ]]; then
		echo run [$CMDMakeCIFForMBJ]
		rm POTCAR
		$CMDMakeCIFForMBJ
		mv POTCAR POTCAR.MBJ
		rm *-Primitive.cif
	fi
	echo run [$CMDMakeCIF]
	$CMDMakeCIF
	cp POTCAR POTCAR.DFT
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,POTCAR.DFT,POTCAR.MBJ} $BackupDir > /dev/null
		cp {*.KPOINTS,*.klist,*.mass} $BackupDir > /dev/null
		cp {*.cif,*.CIF,*.pl,POSCAR.stoc*,*.ini} $BackupDir > /dev/null
	fi
fi

#====================================
# Setup for MBJ
#====================================
if [[ "$METAGGA" != "" ]]; then
	cp POTCAR.DFT POTCAR
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
		if [ "$UseDBRWIGs" = "1" ]; then
			$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
			cp INCAR INCAR.prev
			cp INCAR.RWIGS INCAR
		fi

		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 *.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 *.struct.* *.struct *.xsf *.txt > /dev/null
		$CMDVCRelaxRough

		if [ "$UseDBRWIGs" = "1" ]; then
			$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
			cp INCAR INCAR.prev
			cp INCAR.RWIGS INCAR
		fi

		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

		if [ -f $BaderCMD -a -f "AECCAR0" -a -f "AECCAR2" ]; then
			$CMD --Action=AddCharges AECCAR0 AECCAR2 CHGCAR_sum
			$BaderCMD CHGCAR -ref CHGCAR_sum
			$CMD --Action=SummarizeBader --kVolume=$UpdateRWIGsByRBader . ACF.dat AVF.dat BCF.dat Bader.out
		fi
		
		if [ "$UpdateRWIGsByRBader" != "" ]; then
			$CMD --Action=UpdateRWIGsByRBader . Bader.out
			cp INCAR INCAR.original
		fi

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,POSCAR.initial,OUTCAR,IBZKPT,EIGENVAL,DOSCAR,CONTCAR,CHGCAR} $BackupDir > /dev/null
		cp {XDATCAR,OSZICAR} $BackupDir > /dev/null
		cp {AEC*,PCDAT,PROCAR,REPORT} $BackupDir > /dev/null
		cp {INCAR.RWS,INCAR.original,CHGCAR_sum,ACF.dat,AVF.dat,BCF.dat,Bader.*} $BackupDir > /dev/null
		cp {*.struct,*.struct.out,*.txt,*.cif,*.xsf,DOS*.csv,*.xml,*.html} $BackupDir > /dev/null

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			cp INCAR.RWS INCAR
		fi

		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 *.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 *.initial *.struct.* *.struct *.xsf *.txt > /dev/null
		$CMDVCRelax

		if [ "$UseDBRWIGs" = "1" ]; then
			$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
			cp INCAR INCAR.prev
			cp INCAR.RWIGS INCAR
		fi

		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

		if [ -f $BaderCMD -a -f "AECCAR0" -a -f "AECCAR2" ]; then
			$CMD --Action=AddCharges AECCAR0 AECCAR2 CHGCAR_sum
			$BaderCMD CHGCAR -ref CHGCAR_sum
			$CMD --Action=SummarizeBader --kVolume=$UpdateRWIGsByRBader . ACF.dat AVF.dat BCF.dat Bader.out
		fi

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			$CMD --Action=UpdateRWIGsByRBader . Bader.out
			cp INCAR INCAR.original
		fi

		mkdir $BackupDir
		cp {INCAR,KPOINTS,POTCAR,POSCAR,POSCAR.initial,OUTCAR,IBZKPT,EIGENVAL,DOSCAR,CONTCAR,CHGCAR} $BackupDir > /dev/null
		cp {XDATCAR,OSZICAR} $BackupDir > /dev/null
		cp {AEC*,PCDAT,PROCAR,REPORT} $BackupDir > /dev/null
		cp {INCAR.RWS,INCAR.original,CHGCAR_sum,ACF.dat,AVF.dat,BCF.dat,Bader.*} $BackupDir > /dev/null
		cp {*.struct,*.struct.out,*.txt,*.cif,*.xsf,DOS*.csv,*.xml,*.html} $BackupDir > /dev/null

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			cp INCAR.RWS INCAR
		fi

		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 *.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

#====================================
# Setup for MBJ
#====================================
if [[ "$METAGGA" != "" ]]; then
	cp POTCAR.MBJ POTCAR
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

		if [ "$UseDBRWIGs" = "1" ]; then
			$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
			cp INCAR INCAR.prev
			cp INCAR.RWIGS INCAR
		fi

		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 [ -f $BaderCMD -a -f "AECCAR0" -a -f "AECCAR2" ]; then
			$CMD --Action=AddCharges AECCAR0 AECCAR2 CHGCAR_sum
			$BaderCMD CHGCAR -ref CHGCAR_sum
			$CMD --Action=SummarizeBader --kVolume=$UpdateRWIGsByRBader . ACF.dat AVF.dat BCF.dat Bader.out
		fi

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			$CMD --Action=UpdateRWIGsByRBader . Bader.out
			cp INCAR INCAR.original
		fi

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

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			cp INCAR.RWS INCAR
		fi

		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 '================================================================'
		echo Execute [$CMDSCF]
		$CMDSCF

		if [ "$UseDBRWIGs" = "1" ]; then
			$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
			cp INCAR INCAR.prev
			cp INCAR.RWIGS INCAR
		fi

		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 [ -f $BaderCMD -a -f "AECCAR0" -a -f "AECCAR2" ]; then
			$CMD --Action=AddCharges AECCAR0 AECCAR2 CHGCAR_sum
			$BaderCMD CHGCAR -ref CHGCAR_sum
			$CMD --Action=SummarizeBader --kVolume=$UpdateRWIGsByRBader . ACF.dat AVF.dat BCF.dat Bader.out
		fi

		if [ "$CalLDEnergyForSCF" = "1" ]; then
			echo "$VASPLDCMD --Action=MakeInput ."
			$VASPLDCMD --Action=MakeInput .
			echo "execute [$EnergyPath < LDEnergy.dat | $TEE LDEnergy.out]"
			$EnergyPath < LDEnergy.dat | $TEE LDEnergy.out
		fi

		if [ -f "Bader.out" -a "$CalLDEnergyForSCF" = "1" ]; then
			echo "$VASPLDCMD --Action=MakeInput . Bader.out"
			$VASPLDCMD --Action=MakeInput . Bader.out
			$EnergyPath < LDEnergy-modified.dat | $TEE LDEnergy-modified.out
		fi

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			$CMD --Action=UpdateRWIGsByRBader . Bader.out
			cp INCAR INCAR.original
		fi

		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 {INCAR.RWS,INCAR.original,AEC*,LOCPOT,PCDAT,PROCAR,REPORT} $BackupDir > /dev/null
		cp {XDATCAR,OSZICAR} $BackupDir > /dev/null
		cp {CHGCAR_sum,ACF.dat,AVF.dat,BCF.dat,Bader.*,*.txt,Optics.csv,DOS*.csv,*.xsf,*.xml,*.html} $BackupDir > /dev/null
		cp LDEnergy*.* $BackupDir > /dev/null

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			cp INCAR.RWS INCAR
		fi

		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*} .
		if [ "$UpdateRWIGsByRBader" != "" ]; then
			cp $BaseDir/INCAR.RWS INCAR
		fi
		if [[ "$METAGGA" != "" ]]; then
			cp $BaseDir/POTCAR.MBJ POTCAR
		fi
		
		echo Execute [$CMDDOS .]
		$CMDDOS .

		if [ "$UseDBRWIGs" = "1" ]; then
			$CMD --Action=ChangeRWIGS --RWIGSDB=$RWIGSDB . INCAR.RWIGS
			cp INCAR INCAR.prev
			cp INCAR.RWIGS INCAR
		fi

		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 [ -f $BaderCMD -a -f "AECCAR0" -a -f "AECCAR2" ]; then
			$CMD --Action=AddCharges AECCAR0 AECCAR2 CHGCAR_sum
			$BaderCMD CHGCAR -ref CHGCAR_sum
			$CMD --Action=SummarizeBader --kVolume=$UpdateRWIGsByRBader . ACF.dat AVF.dat BCF.dat Bader.out
			cp INCAR $BaseDir/INCAR.RWS 
		fi

		if [ "$CalLDEnergyForDOS" = "1" ]; then
			echo "Execute [$VASPLDCMD --Action=MakeInput .]"
			$VASPLDCMD --Action=MakeInput .
			echo "Execute [$EnergyPath < LDEnergy.dat | $TEE LDEnergy.out]"
			$EnergyPath < LDEnergy.dat | $TEE LDEnergy.out
		fi
		if [ -f "Bader.out" -a "$CalLDEnergyForDOS" = "1" ]; then
			echo "Execute [$VASPLDCMD --Action=MakeInput . Bader.out]"
			$VASPLDCMD --Action=MakeInput . Bader.out
			echo "Execute [$EnergyPath < LDEnergy-modified.dat | $TEE LDEnergy-modified.out]"
			$EnergyPath < LDEnergy-modified.dat | $TEE LDEnergy-modified.out
		fi

		if [ "$UpdateRWIGsByRBader" != "" ]; then
			$CMD --Action=UpdateRWIGsByRBader . Bader.out
			cp INCAR INCAR.original
		fi

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

		perl $VASPDir/EffectiveMassFromDOS.pl
		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/{*.KPOINTS,*.klist} .
			cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS} .
			if [[ "$METAGGA" != "" ]]; then
				cp $BaseDir/POTCAR.MBJ POTCAR
			fi
			if [ "$HybridFunctional" = "" ]; then
				cp $BaseDir/SCF/{WAV*,CHG*} .
			else 
				cp $BaseDir/DFTSCF/{WAV*,CHG*} .
			fi
			$CMDBandX .

			if [ "$BandKPoints1" == "vaspkit" ]; then
				rm *.KPOINTS
				rm *.klist
				echo ' '
				if [[ "$HybridFunctional" != "" || "$METAGGA" != "" ]]; then
					echo 'Generate KPATH.KPOINTS and KPOINTS by [$VASPKITPATH -task 303]'
					$VASPKITPATH -task 303
					echo 'Generate KPATH.KPOINTS and KPOINTS by [$VASPKITPATH -task 251 -kps G -kpr $kpr_vaspkit -kprb $kpb_vaspkit]'
					$VASPKITPATH -task 251 -kps G -kpr $kpr_vaspkit -kprb $kpb_vaspkit
				else
					echo 'Generate KPATH.KPOINTS and KPOINTS by [$VASPKITPATH -task 303]'
					$VASPKITPATH -task 303
				fi
				mv KPATH.in KPATH.KPOINTS
				cp KPATH.KPOINTS KPOINTS
			else
				cp KPOINTS.band KPOINTS
			fi

			if [ "$LKPOINTS_OPT" == ".TRUE." ]; then
				mv KPOINTS KPOINTS_OPT
				cp $BaseDir/KPOINTS.scf KPOINTS
			fi

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

			perl $VASPDir/EffectiveMassFromBand.pl
			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 "$BandKPoints1" != "vaspkit" -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 [[ "$METAGGA" != "" ]]; then
				cp $BaseDir/POTCAR.MBJ POTCAR
			fi
			if [ "$HybridFunctional" = "" ]; then
				cp $BaseDir/SCF/{WAV*,CHG*} .
			else 
				cp $BaseDir/DFTSCF/{WAV*,CHG*} .
			fi
			$CMDBandY .
			cp KPOINTS.band KPOINTS
			if [ "$LKPOINTS_OPT" == ".TRUE." ]; then
				mv KPOINTS KPOINTS_OPT
				cp $BaseDir/KPOINTS.scf KPOINTS
			fi

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

			perl $VASPDir/EffectiveMassFromBand.pl
			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 "$BandKPoints1" != "vaspkit" -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 [[ "$METAGGA" != "" ]]; then
				cp $BaseDir/POTCAR.MBJ POTCAR
			fi
			if [ "$HybridFunctional" = "" ]; then
				cp $BaseDir/SCF/{WAV*,CHG*} .
			else 
				cp $BaseDir/DFTSCF/{WAV*,CHG*} .
			fi
			$CMDBandZ .
			cp KPOINTS.band KPOINTS
			if [ "$LKPOINTS_OPT" == ".TRUE." ]; then
				mv KPOINTS KPOINTS_OPT
				cp $BaseDir/KPOINTS.scf KPOINTS
			fi

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

			perl $VASPDir/EffectiveMassFromBand.pl
			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

#====================================
# EffectiveMass
#====================================
cd $BaseDir

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

		echo ' '
		echo '================================================================'
		echo "  EffectiveMass run: [$CMDEffectiveMass .]"
		echo '================================================================'

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

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

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

if [ "$StopAfter" = "EffectiveMass" ]; 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*} .
		if [[ "$METAGGA" != "" ]]; then
			cp $BaseDir/POTCAR.MBJ POTCAR
		fi
		$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

#====================================
# Fermi surface
#====================================
cd $BaseDir

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

		cp $BaseDir/hosts .
		cp $BaseDir/SCF/{INCAR,POSCAR,POTCAR,KPOINTS,WAV*,CHG*} .
		if [[ "$METAGGA" != "" ]]; then
			cp $BaseDir/POTCAR.MBJ POTCAR
		fi
		$CMDFS $BackupDir/INCAR

		$VASPFSCMD --Action=MakeKPOINTS --aKProduct=$aKProductFS --UseSymmetry=$UseSymmetryFS \
			   --EFmin=$EFminFS --EFmax=$EFmaxFS

		$VASP | $TEE `hostname`.out.txt
		$VASPFSCMD --Action=MakeBXSF --aKProduct=$aKProductFS --UseSymmetry=$UseSymmetryFS \
			   --EFmin=$EFminFS --EFmax=$EFmaxFS
#		$VASPFSCMD --Action=ViewFS

		rm WAV* CHG* *.FS *.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*} .
		if [[ "$METAGGA" != "" ]]; then
			cp $BaseDir/POTCAR.DFT POTCAR
		fi
		$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*} .
		if [[ "$METAGGA" != "" ]]; then
			cp $BaseDir/POTCAR.DFT POTCAR
		fi
		$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

#====================================
# BoltzTraP2
#====================================
cd $BaseDir

if [ "$CalculateBoltzTraP" = "1" ]; then
	if [ -d "$BaseDir/DOS" ]; then
		BackupDir=$BaseDir/DOS
	else
		BackupDir=$BaseDir/SCF
	fi

	if [ ! -d "$BackupDir" ]; then
		echo "Dir [$BackupDir] does not exist."
		echo "Skip."
	elif [ "$SkipIfDirectoryExists" = "1" -a -e "$BackupDir/interpolation.bt2" ]; then
		echo "Dir [$BackupDir/interpolation.bt2] exists."
		echo "Skip."
	else
		cd $BackupDir
	
		BTP2interpolate="btp2 -vvv interpolate . -e $BoltzTrap_emin -E $BoltzTrap_emax -m $BoltzTrap_ninterp"
		BTP2integrate="btp2 -vvv integrate -b $BoltzTrap_ebin interpolation.bt2 $BoltzTrap_T"
		S2m="python $MSScriptDIR/seebeck2mass.py -t plain"

		echo ' '
		echo '================================================================'
		echo "  BoltzTraP2 interporate: [$BTP2interpolate]"
		echo '================================================================'
#echo [$BTP2interpolate]
		$BTP2interpolate

		echo ' '
		echo '================================================================'
		echo "  BoltzTraP2 integrate: [$BTP2integrate]"
		echo '================================================================'
#echo [$BTP2integrate]
		$BTP2integrate

		echo ' '
		echo '================================================================'
		echo "  Calculate m* from BoltzTraP2 output: [$S2m]"
		echo '================================================================'
#echo [$S2m]
		$S2m
	fi
fi
cd $BaseDir

if [ "$StopAfter" = "BoltzTraP" ]; 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 {EIGENVAL,ELFCAR,LOCPOT,DYNMAT,REPORT,AECCAR*,vasp_raman*} > /dev/null
	rm {INCAR.original,INCAR.RWIGS,INCAR.RWS,ACF.dat,AVF.dat,BCF.dat,Bader.out,CHGCAR_sum} > /dev/null
	rm {CONTCAR,DOSCAR,OUTCAR} > /dev/null
	rm {PCDAT,PROCAR,WAVE*,CHG*} > /dev/null
	rm {DOS-*.csv,*.out,*.struct} > /dev/null
	rm {*.txt,IBZ*} > /dev/null
	rm {LD*} > /dev/null
	rm *.conf *.yaml *.pdf *.dat FORCE* POSCAR-* SPOSCAR
	rm Band*/DOS* > /dev/null
	rm Mass*/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"
