DELIVERY_FOLDER="$(date '+%Y%m%d')_entrega"

mkdir $DELIVERY_FOLDER

# RNASEQ service
cd $DELIVERY_FOLDER

# Links to multiqc reports
ln -s ../../ANALYSIS/*RNASEQ/*rnaseq/multiqc/star_salmon/multiqc_report.html .

# Links to differential expression folders
# REMINDER: please make sure that subfolders within /*_DIFFERENTIAL_EXPRESSION/ follow the structure [number]_*.
# Otherwise, change the following command so that symlinks are created correctly.
# Check this path: /ANALYSIS/[DATE]_ANALYSIS0X_DIFFERENTIAL_EXPRESSION/ to see the names of the folders  
ln -s ../../ANALYSIS/*_DIFFERENTIAL_EXPRESSION/[0-9]*_* .

# Links to counts files
ln -s ../../ANALYSIS/*_RNASEQ/*_rnaseq/star_salmon/salmon.merged.gene_counts.tsv .
ln -s ../../ANALYSIS/*_RNASEQ/*_rnaseq/star_salmon/salmon.merged.gene_tpm.tsv .
ln -s ../../ANALYSIS/*_RNASEQ/*_rnaseq/star_salmon/salmon.merged.transcript_counts.tsv .
ln -s ../../ANALYSIS/*_RNASEQ/*_rnaseq/star_salmon/salmon.merged.transcript_tpm.tsv .
ln -s ../../ANALYSIS/*_RNASEQ/02-differential_expression/99-stats/normalized_expression.csv .


# Prepare data for OmicsExplorer
mkdir OmicsExplorer

ln -s ../../ANALYSIS/*_RNASEQ/03-bigwig/bigwig \
./OmicsExplorer/

ln -s ../../REFERENCES/controls_GTEx_wholeblood_gencode29_gene_TPM_stats.tsv \
./OmicsExplorer/

mkdir -p ./OmicsExplorer/gene_tpm
TPM_FILE=$(realpath ../../ANALYSIS/*_RNASEQ/*_rnaseq/star_salmon/salmon.merged.gene_tpm.tsv)
header=$(head -1 ${TPM_FILE})
samples=$(echo ${header} | cut -f3-)
for sample in ${samples}
do
    awk -v sample="${sample}" '
    BEGIN{
        FS=OFS="\t"
    }
    NR==1{
        for(i=1;i<=NF;i++){
            if($i==sample){
                sample_col=i
            }
        }
        print "gene_id","gene_name",sample
    }
    NR>1{
        print $1,$2,$sample_col
    }
    ' ${TPM_FILE} > ./OmicsExplorer/gene_tpm/${sample}_gene_tpm.tsv
done
