#!/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

# define work and program directory
wd="${file}_Pfold_slow"
pd="$dir/../pfold/bin"

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

# make phylogeny
$pd/findphyl $pd/scfg.rate $wd/input.col | $pd/mltree --quiet $pd/scfg.rate > $wd/tree.col
drawphyl --mult=5 $wd/tree.col > $wd/phylogeny.ps 

# predict structure
$pd/scfg_slow --treeinfile --ppfile $wd/result.pp $pd/article.grm $wd/tree.col | sed 's/arbitrary/RNA/g' > $wd/result.col
drawdot $wd/result.pp > $wd/dotplot.ps

# formatting
addpmasknum $wd/result.col > $wd/result2.col
addpmaskbps $wd/result2.col > $wd/result2x.col
removetree $wd/result2x.col > $wd/result3.col
reliability_colors $wd/result3.col > $wd/result4.col

# plotting
alistem_plot $wd/result4.col

cat $wd/result4.col

# cleaning
#rm $wd/result2.col

exit 0