#!/bin/sh

for gene in `cat Detected_mRNAs`
do wget -O out http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide\&term=Mus+musculus+[orgn]+$gene+[gene]+RefSeq+[filter]+mRNA+[filter]
   sleep 1
   ID=`grep '^<Id>' out | sed -e 's|^<Id>||' -e 's|</Id>||'`
   for id in `echo $ID`
   do wget -O out2 http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore\&id=$id\&rettype=gbwithparts
      sleep 1
      CDS_coord=`grep '^ *CDS ' out2 | awk '{print $2}' | sed 's|\.\.|-|'`
      seq=`sed -e '1,/^ORIGIN *$/ d' -e '/^\/\/$/ d' -e 's|^ *[0-9]* ||' -e 's| ||g' out2 | grep -v '^$' | perl -pe 's/\n//'`
      echo "> "$id" 3´ UTR (with CDS being at "$CDS_coord"); gene: "$gene
      stop=`echo $CDS_coord | sed 's|.*\-||'`
      echo $seq | cut -c `echo $stop"+1" | bc`-
  done
done > Detected_mRNA_UTRs.fa

### Below: because some sequences were not properly retrieved! Probably a download problem: try to re-download.

cat missing_IDs missing_IDs missing_according_to_Blaise | sort | uniq -c | grep '^ *1 ' | awk '{print $2}' > not_done
for id in `cat not_done`
do wget -O out2 http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore\&id=$id\&rettype=gbwithparts
   sleep 1
   if test `grep '^ *CDS ' out2 | grep -c join` -eq 0 # Because some mRNAs have to be further "spliced" (see NM_008753.4 for example), probably because of a sequencing error
   then CDS_coord=`grep '^ *CDS ' out2 | awk '{print $2}' | sed 's|\.\.|-|'`
   else CDS_coord=`grep '^ *CDS ' out2 | sed -e 's|^ *CDS  *join(\([0-9]*\)\.\..*\.\.\([0-9]*\))$|\1-\2|'`
   fi
   CDS_coord=`echo $CDS_coord | sed 's|>||g'` # because some genes have just a minorant of their ending position (see XM_011244540 for example)
   seq=`sed -e '1,/^ORIGIN *$/ d' -e '/^\/\/$/ d' -e 's|^ *[0-9]* ||' -e 's| ||g' out2 | grep -v '^$' | perl -pe 's/\n//'`
   echo "> "$id" 3´ UTR (with CDS being at "$CDS_coord")"
   stop=`echo $CDS_coord | sed 's|.*\-||'`
   echo $seq | cut -c `echo $stop"+1" | bc`-
done > filling_gaps.fa

./Module_fills.pl
mv out.fa Detected_mRNA_UTRs.fa
