#!/usr/bin/env bash

program_dir() {
 local p l
 if [ "${0:0:1}" = "/" ]
 then
   p=$0
 else
   p=$PWD/$0
 fi
 if [ -L "$p" ]
 then
   l=$(find $p -printf '%l')
   if [ "${l:0:1}" = "/" ]
   then
     p=$l
   else
     p=$(dirname $p)/$l
   fi
 fi
 echo $(dirname $p)
} 

dir=$(program_dir)

if [ -e "$2" ]
then
	file="$2"
	range="$1"
else
	file="$1"
	range=" "
fi

# set work directory
wd="${file}_Pfold_groups"

# prepare
mkdir $wd
stripit ${file} > $wd/input.col

# make groups files
col2list $wd/input.col > $wd/dot.txt

stripit2 ${file} > $wd/input.col
col2fasta $wd/input.col > $wd/input.fasta

# make structures
makestruc.tcsh $wd/input.fasta $wd/dot.txt ${range} > $wd/result.col
reassemble $wd/result.col $wd/input.col ${range} > $wd/result2.col
addpmaskpar $wd/result2.col > $wd/result3.col

# color grouped alignment
addit2 ${file} $wd/result3.col > $wd/result4.col
reliability_colors $wd/result4.col > $wd/result5.col

# make plots
makeplots.tcsh $wd/input.fasta $wd/dot.txt ${range}
alistem_plot $wd/result5.col

# send to SARSE
cat $wd/result5.col

#cleaning
#mv plot*.pp $wd/ 2> /dev/null
#mv tree*.ps $wd/ 2> /dev/null
#rm $wd/result2.col $wd/result3.col $wd/result.col $wd/input.col $wd/input.fasta $wd/dot.txt

exit 0
