#!/bin/bash

if [ $# -lt 4 ]; then
  echo 'gencell <volume> <units> n x [<species> <number>]'
  exit 1
fi

numspecies=`echo "($#-2)/2" | bc`

seedname=`for i in ${*:2}
do
if [ $i != "1" ]; then
echo -n $i
fi
done`
length=`echo "scale=6;e(l($1)/3.0)" | bc -l`

# Prepare the cell file
cat<<EOF>$seedname.cell
%BLOCK LATTICE_CART
$length 0 0
0 $length 0
0 0 $length
%ENDBLOCK LATTICE_CART

#VARVOL=$1 

%BLOCK POSITIONS_FRAC
EOF
for (( i = 1; i <= $numspecies; i++ ))  
  do
    num=0
    for (( j = 1; j <= $2; j++ ))  
    do
	for (( k = 1; k <= ${*:$[2*($i-1)+4]:1}; k++ ))  
	do
	    num=$[$num+1]
	    
	    echo ${*:$[2*($i-1)+3]:1}' 0.0 0.0 0.0 # '${*:$[2*($i-1)+3]:1}$num' % NUM=1' >> $seedname.cell
	    
	done
    done
done
cat<<EOF>>$seedname.cell
%ENDBLOCK POSITIONS_FRAC

EOF
echo -n '##SPECIES='  >> $seedname.cell
for (( i = 1; i <= $numspecies; i++ ))
do
    species=${*:$[2*($i-1)+3]:1}
    echo -n $species >> $seedname.cell
    if [[ $i < $numspecies ]]; then
	echo -n ',' >> $seedname.cell
    else
	echo >> $seedname.cell
    fi
done
cat<<EOF>>$seedname.cell
##NATOM=3-9
##FOCUS=$numspecies
 
#SYMMOPS=2-4
##SGRANK=20
#NFORM=1
##ADJGEN=0-1
#SLACK=0.25
#OVERLAP=0.1
#MINSEP=1-3 AUTO
#COMPACT
#CELLADAPT
##SYSTEM={Rhom,Tric,Mono,Cubi,Hexa,Orth,Tetra}
 
KPOINTS_MP_SPACING 0.07
 
SYMMETRY_GENERATE
SNAP_TO_SYMMETRY
 
%BLOCK SPECIES_POT
QC5
%ENDBLOCK SPECIES_POT
 
%BLOCK EXTERNAL_PRESSURE
0 0 0
0 0
0
%ENDBLOCK EXTERNAL_PRESSURE
EOF

# Prepare the param file

cat<<EOF>$seedname.param
task                 : geometryoptimization
xc_functional        : PBE 
spin_polarized       : false 
fix_occupancy        : false 
metals_method        : dm 
mixing_scheme        : pulay 
max_scf_cycles       : 1000 
cut_off_energy       : 340 eV
opt_strategy         : speed 
page_wvfns           : 0 
num_dump_cycles      : 0 
backup_interval      : 0 
geom_method          : LBFGS 
geom_max_iter        : 20 
mix_history_length   : 20 
finite_basis_corr    : 0
fixed_npw            : true
write_cell_structure : true
write_checkpoint     : none
write_bib            : false
write_otfg           : false
write_cst_esp        : false
write_bands          : false
write_geom           : false
bs_write_eigenvalues : false
calculate_stress     : true
EOF

exit 0
