#!/bin/bash

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

#SBATCH --time=3-00:00
#SBATCH --mem-per-cpu=37G
#SBATCH --cpus-per-task=20

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

# $1 = ACH.MIL ...  
#########################################################################################################
# Paths and filenames for this analysis
# 
dDOCENT_DIR=/data/Popgen/programs/ddocent-2.9.4/bin
dDOCENT_DIR_local=/gpfs1/data/Popgen/2021_RegioDiv/dDocent_files

#BASE_DIR=/work/durka/dDocent/RegioDiv
# BASE_DIR=/work/%u/dDocent/RegioDiv # %u funktioniert so nicht !!
BASE_DIR=/work/durka/dDocent/RegioDiv
WORK_DIR=$BASE_DIR/$1/
#WORK_DIR=/gpfs1/work/durka/dDocent/RegioDiv/ANT.DIO.cut
mkdir $WORK_DIR
mkdir $WORK_DIR/data.tmp

#mkdir /work/%u/dDocent
#mkdir /work/%u/dDocent/RegioDiv
#mkdir $WORK_DIR

# WORK_DIR: here are the correctly named outputfiles of process_radtags, copied from
# e.g. /gpfs1/data/Popgen/2021_RegioDiv/Spec28.fq/ACH.MIL.disable_radcheck
DATA_DIR=/gpfs1/data/Popgen/2021_RegioDiv/Spec28.fq/"$1".disable_radcheck
#DATA_DIR=/gpfs1/work/durka/dDocent/RegioDiv/Spec28.fq/
#cd "$DATA_DIR"LYC.FLO.disable_radcheck/
cd "$DATA_DIR"
cp *.gz $WORK_DIR/data.tmp

# since sequencing used too little PhiX, the first 5/3 bases ahave low phred-scroes in F/R reads
# Thus it is necessary to cut these bases
########## Cutadapt ##########
## "old code" August 2023
## load cutadapt
#module load foss/2018b cutadapt/1.18-Python-3.6.6
## necessary for pigz
#module load GCCcore/10.2.0
## enable parallel compression
#module load pigz/2.6

# necessary for cutadapt , pigz
module load GCCcore/12.2.0

# load cutadapt
module load foss/2022b cutadapt/4.4
#module spider cutadapt

# enable parallel compression
#module spider pigz

cd $WORK_DIR/data.tmp

#for library in ./*batch02*/
#do
#   libraryname=$(basename $library)
#   mkdir -p "${out}${libraryname}"
#   cd $library
   indnames=$(find . -type f | grep -Eo '[A-Z]{3}\.[A-Z]{3}.*[A-Z][0-9]{2}' | sort | uniq)
   for indname in $indnames
   do
      fastq1="./${indname}.R.fq.gz"
      fastq2="./${indname}.F.fq.gz"
      # --cores=0 auto-detects number of available cores
      cutadapt \
         --cores=0 \
         --cut 5 \
         -U 3 \
         --output "${WORK_DIR}/${fastq1}" \
         --paired-output "${WORK_DIR}/${fastq2}" $fastq1 $fastq2
   done
#   cd $in
#done



#########################################################################################################

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/ddocent-2.9.4

cp "$dDOCENT_DIR"/dDocent_2x $WORK_DIR

cp "$dDOCENT_DIR_local"/Configuration_01_20cpu $WORK_DIR

cd $WORK_DIR
./dDocent_2x Configuration_01_20cpu

conda deactivate

