#!/bin/bash
#The script is used to cut out parts of the protein chain. The main purpose is to get rid off loops that are added to the contact map matrix prior
#to ftcomar rebuilding of a structure.
#USAGE:
#cmap_trim_loops <pdb_file_name> <loop_length> <insertion_pt1> <insertion_pt2>...
#cmap_trim_loops <pdb_file_name> -f <file_path>



EXPECTED_ARGS=3;
BAD_ARGS=1;
NOT_SUPPORTED=2;

if [ $# -lt ${EXPECTED_ARGS} -o "$1" == "help" ]
then
        echo "USAGE:"
        echo "cmap_trim_loops <pdb_file_name> <loop length> <insertion_pt1> <insertion_pt2> ..."
        echo "cmap_trim_loops <pdb_file_name> -f <file_path>"
        exit $BAD_ARGS
fi
pdb_file_name=$1;
counter=0;
if [ $2 == "-f" ]
then 
        echo "Reading loop file: $3"
        echo "File reading not supported yet"   
        exit $NOT_SUPPORTED
else
        loop_length=$2
        echo "Chosen loop length: $loop_length"
        for i in  ${@:3:$#}
        do
                trim_pt1=$[$i+1]
		trim_pt2=$[$trim_pt1+$loop_length-1]
                echo "Triming loop at residues:" $trim_pt1 $trim_pt2
		if [ $counter -eq "0" ]
		then
			sed -i~ ${trim_pt1},${trim_pt2}d ${pdb_file_name} 
		else
			sed -i ${trim_pt1},${trim_pt2}d ${pdb_file_name} 
		fi
		counter=$[$counter+1]
        done
fi


mv ${pdb_file_name}~ ${pdb_file_name%%.*}_loops.pdb
