#!/bin/bash

while getopts hvf:o:i:n:j:ep opt; do
  case $opt in
    h)
      echo ""
      echo " ------------------------------------------------------------------------------ "
      echo " superdenss is a simple wrapper for denss that automates the process of "
      echo " generating multiple density reconstructions and averaging them with EMAN2. "
      echo ""
      echo " -h: Print this help text and exit"
      echo " -v: print denss.py version number and exit"
      echo " -f: filename of .out GNOM file or .dat solution scattering data"
      echo " -o: the output prefix to name the output directory and all the files."
      echo " -i: input options for denss exactly as they would be given to denss, including"
      echo "     dashed options. Enclose everything in quotes. Dont include --file or --output."
      echo " -n: the number of reconstructions to run (default 20)"
      echo " -j: the number of cores to use for parallel processing (default one less than system)"
      echo " -e: generate and select enantiomers (significantly increases runtime, default=no)"
      echo " -p: turn off plotting (default is to plot)"
      echo " ----------------------------------------------------------------------------- "
      echo ""
      exit 0
      ;;
    v)
      version=True
      ;;
    f)
      file=$OPTARG
      ;;
    o)
      output=$OPTARG
      ;;
    i)
      options=$OPTARG
      ;;
    n)
      n=$OPTARG
      ;;
    j)
      j=$OPTARG
      ;;
    e)
      enantiomers=True
      ;;
    p)
      plot=False
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." #>&2
      exit 1
      ;;
  esac
done

if [ "$version" == "True" ];
then
    denss.py --version
    exit
fi

if [ -z $output ];
then
    output=${file%.*}
fi

id=$output

if [ -z $n ]; then n=20 ; fi
range=`eval echo {0..$((n-1))}`
if [ -z $j ];
then
    cores=`getconf _NPROCESSORS_ONLN 2>/dev/null || getconf NPROCESSORS_ONLN 2>/dev/null || echo 1` ;
    if [ $cores -eq 1 ];
    then
        j=`echo $cores | awk '{print $1}'`
    else
        j=`echo $cores | awk '{print $1-1}'`
    fi
fi
echo "Using $j processors"
dir=${output}
newdir=$dir
dirn=0

until [ ! -d "${newdir}" ];
do
    newdir=${dir}_${dirn}
    let dirn++
done

if [ ! -d "${newdir}" ];
then
    mkdir $newdir
fi

cp ${file} ${newdir}/
cd $newdir
pwd
echo "superdenss $@" > command

if [ "${plot}" == "False" ];
then
    options="${options} --plot_off"
fi

printf "Running denss.py %i times \n" $n

if [ `command -v parallel` ];
then
    parallel -j ${j} denss.py -f \{1} -o \{2}_{3} ${options} ::: ${file} ::: ${id} ::: ${range}
else
    for i in ${range};
    do
        denss.py -f ${file} -o ${id}_${i} ${options}
    done
fi

e2version=`e2version.py | awk 'NR==1 {print $2}'`
e2new=`echo $e2version'>'2.21 | bc -l`

if [ "$enantiomers" == "True" ];
then
    maps=`ls ${id}*[0-9].mrc`
    best_enantiomers.sh -f "$maps" -j $j
    #Now run averaging using just the best enantiomers
    if [ $e2new -eq 1 ];
    then
      e2buildstacks.py --output ${id}.hdf ${id}*enant.hdf
    else
      e2buildstacks.py --stackname ${id}.hdf ${id}*enant.hdf
    fi
else
    if [ $e2new -eq 1 ];
    then
      e2buildstacks.py --output ${id}.hdf ${id}*[0-9].mrc
    else
      e2buildstacks.py --stackname ${id}.hdf ${id}*[0-9].mrc
    fi
fi

e2spt_binarytree.py --parallel=thread:${j} --path=spt_bt_ref --input=${id}.hdf
cp spt_bt_ref_01/final_avg.hdf reference.hdf
e2spt_classaverage.py --path=spt_avg --input ${id}.hdf --ref reference.hdf --parallel=thread:${j} --saveali --savesteps --keep 3.0 --keepsig
e2proc3d.py spt_avg_01/final_avg_ali2ref.hdf ${id}_avg.mrc
#cp spt_avg_01/fsc_0.txt ${id}_fsc.txt
#fsc2res.py -f ${id}_fsc.txt

#Alternative resolution calculation
halfn=`echo $n | awk '{print int($1/2)}'`
halfrange=`eval echo {0..$((halfn-1))}`
for i in ${halfrange};
do
    e2proc3d.py --calcfsc=${id}_avg.mrc spt_avg_01/aliptcls_even.hdf ${id}_even_$i.fsc --first $i --last $i
    e2proc3d.py --calcfsc=${id}_avg.mrc spt_avg_01/aliptcls_odd.hdf ${id}_odd_$i.fsc --first $i --last $i
done

if [ "${plot}" == "False" ];
then
    fsc2res.py -f ${id}_even_*.fsc ${id}_odd_*.fsc -o ${id}_fsc.dat --plot_off
else
    fsc2res.py -f ${id}_even_*.fsc ${id}_odd_*.fsc -o ${id}_fsc.dat --plot_on
fi




