#!/bin/bash
#####
# Add functional annotations to the High/Low confidence gene models
#####

mkdir -p tmp

# LowConf gene models
cut -f1,5,10-12 references/RefSeq_v1.0/iwgsc_refseqv1.0_FunctionalAnnotation_v1__LCgenes_v1.0.tab \
  | mawk -f add_func_annot.awk \
  | sed 's/;\+/;/; s/;$//; 1d;' \
  > tmp/iwgsc_refseqv1.0_FunctionalAnnotation_v1__LCgenes_v1.0.gff3_attributes
awk 'BEGIN{FS="\t";OFS="\t"}NR==FNR{a["ID="$1]=$2;next}{match($9,"ID=[^;]+",id);if(a[id[0]]){print $0";"a[id[0]];}else{print}}' \
  tmp/iwgsc_refseqv1.0_FunctionalAnnotation_v1__LCgenes_v1.0.gff3_attributes \
  <(pigz -dcp2 references/RefSeq_v1.0/iwgsc_refseqv1.0_LowConf_UTR_2017May05.parts.gff3.gz) \
  | bgzip \
  > references/RefSeq_v1.0/iwgsc_refseqv1.0_LowConf_UTR_2017May05.parts.annotated.gff3.gz
tabix references/RefSeq_v1.0/iwgsc_refseqv1.0_LowConf_UTR_2017May05.parts.annotated.gff3.gz

# HighConf gene models
cut -f1,5,10-12 references/RefSeq_v1.0/iwgsc_refseqv1.0_FunctionalAnnotation_v1__HCgenes_v1.0.tab \
  | mawk -f add_func_annot.awk \
  | sed 's/;\+/;/; s/;$//; 1d;' \
  > tmp/iwgsc_refseqv1.0_FunctionalAnnotation_v1__HCgenes_v1.0.gff3_attributes
awk 'BEGIN{FS="\t";OFS="\t"}NR==FNR{a["ID="$1]=$2;next}{match($9,"ID=[^;]+",id);if(a[id[0]]){print $0";"a[id[0]];}else{print}}' \
  tmp/iwgsc_refseqv1.0_FunctionalAnnotation_v1__HCgenes_v1.0.gff3_attributes \
  <(pigz -dcp2 references/RefSeq_v1.0/iwgsc_refseqv1.0_HighConf_UTR_2017May05.parts.gff3.gz) \
  | bgzip \
  > references/RefSeq_v1.0/iwgsc_refseqv1.0_HighConf_UTR_2017May05.parts.annotated.gff3.gz
tabix references/RefSeq_v1.0/iwgsc_refseqv1.0_HighConf_UTR_2017May05.parts.annotated.gff3.gz
