#!/bin/bash

# Serial_Trimmer.sh: this script takes the output from the LS³ bash script bundle and trims from each complete dataset the branches that were including too much branch length heterogeneity.

#***IMPORTANT***
# Alignment files must be in the same folder, in FASTA format, with .fas as the extension. (NOT Phy format, as the LS³ pipeline requires).

# Usage:
# %s <LS3_trimResults_table.csv> <allsppcladesfile.csv>

linefile=$1
sppcl=$2

for line in $(cat $linefile)
do
  alignment_phy=$(echo $(echo $line | cut -d"," -f1).phy)
  alignment_fas=$(echo $(echo $line | cut -d"," -f1).fas)
  threshold=$(echo $line | cut -d"," -f2 | cut -d"." -f2)
  gene=$(echo $line | cut -d"," -f1 | sed 's/.phy//g')
  tokill=$(echo $line | cut -d"," -f5 | tr ";" "\n")
  trimstep=$(echo $line | cut -d"," -f3)
  if [[ -z "$trimstep" ]]
  then
    echo "$gene never reached homogeneity"

  elif [[ "$trimstep" == "0" ]]
  then
    echo "$gene - trimming not necessary - copying alignment to "$gene"_p"$threshold"_trimmed.phy"

    cp $alignment_fas "$gene"_p"$threshold"_trimmed.fas
  else
    echo $(cut -d"," -f2 $sppcl) $tokill | tr [:blank:] "\n" | sort | uniq -u > "$gene"_savedtaxa.csv
    echo "Trimming alignment from gene $gene..."

    alignment=$alignment_fas
    livingtaxa="$gene"_savedtaxa.csv
    outfile="$gene"_p"$threshold"_trimmed.fas

    genename=$(echo $alignment | sed 's/.fas//g')

    m=0
    sed -i 's/://g' $alignment
    for k in $(for i in $(grep ">" $alignment)
     do
      new=$(echo $i:)
      sed -i "s/$i$/$new/g" $alignment
     done
     cat $alignment | tr -s ":" | tr -d "\n" | sed 's/>/\n>/g')
    do
     dataarray[$m]=$k
     m=$(echo $m+1 |bc)
    done


    for i in $(cut -d"," -f1 $livingtaxa)
    do
     echo ${dataarray[*]} | sed 's/ >/\n>/g' | grep "$i:" | sed 's/:/\n/g' | tr -d " "| fold -w60 >> $outfile;
    done
     sed -i 's/://g' $alignment

 fi
done

