#!/bin/bash

mkdir -p ../fastasubseq
mkdir -p ../fastasubseq/fastafetx
mkdir -p ../fastasubseq/fastasubseqexit

for year_d in ../hits/* ; do {
	year=`basename $year_d`	
	mkdir -p ../fastasubseq/fastafetx/$year 2> error_msg.txt
	mkdir -p ../fastasubseq/fastasubseqexit/$year 2> error_msg.txt

for genome_d in ../hits/$year/* ; do {
	genome=`basename $genome_d`
	mkdir -p ../fastasubseq/fastafetx/$year/$genome 2> error_msg.txt
	mkdir -p ../fastasubseq/fastasubseqexit/$year/$genome 2> error_msg.txt

for query_original in ../hits/$year/$genome/*; do {

	query=`basename $query_original`
echo $query
	mkdir -p ../fastasubseq/fastasubseqexit/$year/$genome/$query 2> error_msg.txt
	mkdir -p ../fastasubseq/fastafetx/$year/$genome/$query 2> error_msg.txt
	
	for hit_carpeta_d in ../hits/$year/$genome/$query/*; do {
	
		hit_carpeta=`basename $hit_carpeta_d`
	echo $hit_carpeta
		mkdir -p ../fastasubseq/fastasubseqexit/$year/$genome/$query/$hit_carpeta 2> error_msg.txt
		mkdir -p ../fastasubseq/fastafetx/$year/$genome/$query/$hit_carpeta 2> error_msg.txt


	for hit in ../hits/$year/$genome/$query/$hit_carpeta/*; do {
				
		nom=`basename $hit`
		
		contig=`cut -f2 $hit`
		echo $contig $nom
		fastafetch /cursos/BI/genomes/protists/2011/$genome/genome.fa /cursos/BI/genomes/protists/2011/$genome/genome.index $contig > ../fastasubseq/fastafetx/$year/$genome/$query/$hit_carpeta/fastafetch_$nom 

		start=`cut -f9 $hit`
		length=`cut -f10 $hit`

		mespetit=`perl mespetit.pl $start $length`
echo $mespetit
		startfinal=`perl start.pl $mespetit`
echo $startfinal
		lengthfinal="30000"

		fastasubseq ../fastasubseq/fastafetx/$year/$genome/$query/$hit_carpeta/fastafetch_$nom $startfinal $lengthfinal > ../fastasubseq/fastasubseqexit/$year/$genome/$query/$hit_carpeta/fastasubseq_$nom 2> error_msg.txt

### Això ens servirà per modificar variables en cas que no hi hagi prou bases en la contig o que l'inici estigui massa aprop
                   
    error=`cat error_msg.txt`
    if [ "$error" != "" ]; then
            error_llarg=`cat error_msg.txt | egrep "before end"`
            
                       
        ### Si es passa de llarg, establim la llargada perquè arribi al final
        if [ "$error_llarg" != "" ]; then
            llargada=$error_llarg                       
            llargada=${llargada##*(}
            llargada=${llargada%)}
            lengthfinal=$(( $llargada - $startfinal)) 
            fastasubseq ../fastasubseq/fastafetx/$year/$genome/$query/$hit_carpeta/fastafetch_$nom $startfinal $lengthfinal > ../fastasubseq/fastasubseqexit/$year/$genome/$query/$hit_carpeta/fastasubseq_$nom 2> error_noio.txt
        fi
                       
    fi	} done
} done
	} done
} done
} done
  rm ./*.txt
