#!/bin/bash


#Usage:
# ./LS*_tabs <LS3_trimResults_table.csv> <allsppcladesfile.csv> "RUNNAME"

results_table=$1
sppcladesfile=$2
runname=$3

echo "FIRST LOOP"...
#The first for loop goes through each gene (that survived LS³ trimming), and writes the name of the species that were flagged into a master list
for i in $(grep -v ",," $results_table | cut -d"," -f1)
do
  echo "Gene "$i""
  grep ">" $i.fas | sed 's/>//g' > init_seqs.tmp
  grep ^$i, $results_table | cut -d"," -f5 | tr ";" "\n" > absent_seqs.tmp
  cat init_seqs.tmp absent_seqs.tmp | sort -d | uniq -d >> total_flagged.tmp
  rm init_seqs.tmp absent_seqs.tmp
done

#The second for loop goes through each sequence and counts how often it was flagged, how often it appeared, and calculates a percentage of times it was flagged.

#***This is still using only the genes that survived LS³ trimming***
echo "SECOND LOOP"
echo "Species,Genes.flagged,Total.genes,Percentage.flagged" > "$runname"_flagged-spp.csv
for i in $(grep "Clade" $sppcladesfile | cut -d"," -f2)
do 
  app=$(grep -o ^$i$ total_flagged.tmp | wc -l)
  totapp=$(cat $(grep -v ",," $results_table | cut -d"," -f1 | sed 's/$/.fas/g') | grep ">$i$" | wc -l)
  prop=$(echo "scale=4; $app/$totapp*100" | bc)
  echo $i,$app,$totapp,$prop
done | sort -r -k4 -t"," -h >> "$runname"_flagged-spp.csv

rm total_flagged.tmp

#This loop checks for all species on all genes that survived LS³ trimming whether they were 1) absent from the dataset ("NA"), 2) present, but flagged by LS³ ("0"), or 3) present, and not flagged ("1").
#In other words, it makes the raw data table for a heat map

echo $(cut -d"," -f2 $sppcladesfile | sed 's/^/,/g' | tr -d [:space:]; echo) > "$runname"_heat_mapdata.csv
echo "THIRD LOOP"
for gene in $(grep -v ",," $results_table | cut -d"," -f1);
do
  echo "Gene "$gene""
  echo $gene,$(for i in $(cut -d"," -f2 $sppcladesfile ); do init=$(grep ">$i$" $gene.fas); tri=$(grep -v ",," $results_table | grep $gene, | cut -d"," -f5 | tr ";" "\n" | grep ^$i$); if [[ -z "$init" ]]; then echo "NA,"; elif [[ "$init" ]] && [[ -z "$tri" ]]; then echo "1,"; elif [[ "$init" ]] && [[ "$tri" ]]; then echo "0,"; fi; done | tr -d [:space:] | sed 's/,$/\n/g') >> "$runname"_heat_mapdata.csv
  done

