#!/bin/bash
# Grid Engine Options
#$ -l c7
#$ -N Squeeze_VE_Preprocess
#$ -l h_vmem=4G,h_rt=03:00:00
#$ -j y
#$ -pe mp 21

INPUTDIR=/SCRATCH/cricasre/Metagen/trimming # SAMPLE directory
SCRIPTSDIR=/home/grupos/gen/Monica/Metagenomics/scripts #Statistics
PROGRAMDIR=/home/grupos/gen/Monica/programs #Quality control
RAW=/SCRATCH/cricasre/fastq
FILTERDIR=/SCRATCH/cricasre/Metagen/filter2
HOSTDB=/home/grupos/gen/rabbit_v101/host_DB
MINICONDADIR=/home/grupos/gen/miniconda3/bin
SQUEEZEDIR=/home/cricasre/SqueezeMeta

### Paralellize samples ###
SAMPLE=$(awk 'NR==n {print;exit}' n=$SGE_TASK_ID /home/cricasre/files/samples_trim.txt)

### Filter host genome ###
DT=$(date "+%Y/%m/%d %H:%M:%S")
echo "$DT:Filter DNA host"

mkdir -p $FILTERDIR
cd $FILTERDIR

echo "Botwie"
bowtie2 -x $HOSTDB -p 21 -1 $RAW/${SAMPLE}_R1.fastq -2 $RAW/${SAMPLE}_R2.fastq -S ${SAMPLE}_MU.sam
 
echo "Samtools"
samtools view -@ 21 -bS ${SAMPLE}_MU.sam > ${SAMPLE}_MU.bam
rm ${SAMPLE}_MU.sam

### Filter unmapped reads ###
echo "Filter"
samtools view -@ 21 -b -f 12 -F 256 ${SAMPLE}_MU.bam > ${SAMPLE}_both.bam
rm ${SAMPLE}_MU.bam

### Split paired-end reads ###
samtools sort -@ 21 -n ${SAMPLE}_both.bam ${SAMPLE}_both_sorted
rm ${SAMPLE}_both.bam

$MINICONDADIR/bedtools bamtofastq -i ${SAMPLE}_both_sorted.bam -fq ${SAMPLE}_filter_R1.fastq -fq2 ${SAMPLE}_filter_R2.fastq
rm ${SAMPLE}_both_sorted.bam


