# $1 = person ID
personID=$1

dirBase=/grid/dobin/home/dobin/Projects/Consensus/ConsensusSimulations/
STAR=$dirBase/STAR
seqErrRate=0.005
id_table=/grid/dobin/home/kaminow//reference/consensus_mapping/id_table.csv

################################## Pop and Sup genones
genome_sup=`grep ^$personID $id_table | awk -F, '{print $2}'`
genome_pop=`grep ^$personID $id_table | awk -F, '{print $3}'`

echo $genome_pop $genome_sup

##################################
mkdir -p $personID
cd $personID && pwd
[[ ! -e PersReads.fa ]] && awk -v readLen=50 -b -O -f $dirBase/scripts/TrToG.awk    $dirBase/vcf/$personID/$personID.vcf > PersReads.fa

echo removeDuplicates
[[ ! -e PersReads.fa.unique2.fa ]] && $dirBase/scripts/removeDuplicates.sh PersReads.fa

mkdir -p STARpersonal
cd STARpersonal && pwd

[[ ! -e Aligned.out.sam ]] && \
   $STAR --genomeDir $dirBase/genomes/$personID/ --outSAMunmapped Within --outFilterMultimapNmax 1000 --readFilesIn ../PersReads.fa.unique2.fa --alignEndsType EndToEnd --outFilterMismatchNmax 0

[[ ! -e NoMulti.fa ]] && awk '$1!~/^@/ && substr($12,6)+0<=1 {print ">" $1; print $10}' Aligned.out.sam > NoMulti.fa

cd ..

faFinal=NoMulti_err$seqErrRate.fa
[[ ! -e $faFinal ]] && awk -b -O -v errRate=$seqErrRate   -f $dirBase/scripts/addErrRate.awk   STARpersonal/NoMulti.fa   > $faFinal

#################################### ref and pan
for genome1 in ref pan sup pop pers
do
    [[ ! -e $genome1 ]] && mkdir $genome1 
    cd $genome1 
    if [[ ! -e Aligned.out.sam ]]; then
       echo Mapping to $genome1
       genomeDir=$genome1
       transformOutput=SAM
       [[ $genome1 == ref ]] && transformOutput=None
       [[ $genome1 == sup ]] && genomeDir=$genome_sup
       [[ $genome1 == pop ]] && genomeDir=${genome_sup}_$genome_pop
       [[ $genome1 == pers ]] && genomeDir=$personID
       $STAR --genomeDir $dirBase/genomes/$genomeDir --readFilesIn ../$faFinal --outSAMunmapped Within \
             --outFilterMultimapNmax 1000 --genomeTransformOutput $transformOutput
    fi
    cat Aligned.out.sam | awk -f $dirBase/scripts/calcErrorRate.awk > Errors.stats
    cd ..

done
