#!/bin/bash

#SBATCH --job-name=dDocent_make_inputfiles
#SBATCH --mail-user=walter.durka@ufz.de
#SBATCH --mail-type=BEGIN,END,FAIL,TIME_LIMIT

#SBATCH --time=24:00:00
#SBATCH --mem-per-cpu=8G
#SBATCH --cpus-per-task=1

# output files
#SBATCH --output=/work/durka/%x-%j.out
#SBATCH --error=/work/durka/%x-%j.err

#########################################################################################################
# make this file executable: 
#########################################################################################################

cd $WORK_DIR || exit

mkdir $3 #DATA_DEMUXtemp_01

module load Anaconda3
source $(dirname $(which conda))/../etc/profile.d/conda.sh 
#conda activate /data/Popgen/programs/stacks-2.53
#conda activate /data/Popgen/programs/stacks-2.65
conda activate /data/Popgen/programs/ddocent-2.9.4


# $1 forwardreads
# $2 reversereads
# $3 output dir = $DATA_DEMUXtemp_01
# $4 barcode file

process_radtags --paired -1 $1 -2 $2 -o $3 -i gzfastq -y gzfastq -b $4 --barcode_dist_1 2 --barcode_dist_2 2 --inline_index --renz_1 'ecoRI' --renz_2 'mspI' --disable_rad_check --retain_header

# rename the demultiplexed files with true sample names and 
# concatenate files if there are multiple barcode/index combinations for the same sample. 
cat $4 | while read line
do
    echo "$line"
    bc=$(echo "$line" | cut -f1 | cut -d" " -f1) 
    id=$(echo "$line" | cut -f2 | cut -d" " -f2) 
    name=$(echo "$line" | cut -f3 | cut -d" " -f3 | tr -d '\r') 
# correclty named demultiplexed files must go to a directory in which only these are present
    mv $3/"$name".1.fq.gz $3/"$name".F.fq.gz
    mv $3/"$name".2.fq.gz $3/"$name".R.fq.gz
done 

conda deactivate

# zip the files
#for i in $WORK_SUBDIR/*fq
#do
#   echo "$i" 
#   gzip $i
#done
