#!/bin/bash
set -e;
email_address_of_user=$1;
echo "email: " $email_address_of_user;

echo "Calculation of Y-linked genes started."
./scripts/prepare_statistics.sh;
echo "Statistics done";
	
#filter contigs, which are candidate Y genes - very divergent from their X counterparts
perl scripts/filter_diverged_Y_contigs.pl scripts/statistics/stat_mother scripts/statistics/stat_father scripts/statistics/stat_daughter scripts/statistics/stat_son >Y_results.txt;
perl scripts/get_sequences_based_on_ids.pl references/reference_male.fasta Y_list >Y_results_sequences.txt;

if [[ -s Y_list ]] ; then
	get_results_in_bam_file () 
	{
	  for ARG in "$@";
	    do
	    	./scripts/createBamFromResults.sh Y_list bam/aln_cleaned_sorted_deduplicated_${ARG}_male.bam bam/${ARG}_male.bam;
	    	samtools index bam/${ARG}_male.bam;
	    done;
	}

	get_results_in_bam_file mother father daughter son;
	wait;
	#send BAM files with corresponding contigs
	mutt -s "LINKYX: Results of computation for Y-linked genes" $email_address_of_user -a bam/mother_male.bam -a bam/mother_male.bam.bai -a bam/father_male.bam -a bam/father_male.bam.bai -a bam/daughter_male.bam -a bam/daughter_male.bam.bai -a bam/son_male.bam -a bam/son_male.bam.bai < messages_to_user/message_results_sentBamY;
else 
		#we found NO genes
		echo "No sequences found." >Y_results.txt;
		echo "No sequences found." >Y_results_sequences.txt;
fi