#PBS -q bl2x220g7q
#PBS -l select=1:ncpus=5:mem=10g
#PBS -l walltime=3:00:00
#PBS -l cput=30:00:00


export PATH=$PATH:~/programms/bwa-0.7.17;
WORK_DIR=~/loxP_project/2022-03-11_rings/
cd $WORK_DIR; mkdir align; 
cd align;
declare -a files=("S3cDiNA")
for file in "${files[@]}"
do
echo ${file}
mkdir ${file}
cat $WORK_DIR/cutadapt/${file}_1.fq | grep ada1 -A 4 >> $WORK_DIR/cutadapt/${file}_ada1.fq
cat $WORK_DIR/cutadapt/${file}_2.fq | grep ada1 -A 4 >> $WORK_DIR/cutadapt/${file}_ada1.fq
cat $WORK_DIR/cutadapt/${file}_1.fq | grep ada2 -A 4 >> $WORK_DIR/cutadapt/${file}_ada2.fq
cat $WORK_DIR/cutadapt/${file}_2.fq | grep ada2 -A 4 >> $WORK_DIR/cutadapt/${file}_ada2.fq
## align ada1
bwa mem -t 5 -M -R '@RG\tID:${file}_ada1' /mnt/storage/home/psbelokopytova/insulatory_index/bds_pipeline_genome_data/hg38/bwa_index/GRCh38_no_alt_analysis_set_GCA_000001405.15.fasta $WORK_DIR/cutadapt/${file}_ada1.fq | samtools view -bS -@ 5 | samtools sort > $WORK_DIR/align/${file}/${file}_ada1.sorted.bam;
samtools index $WORK_DIR/align/${file}/${file}_ada1.sorted.bam > $WORK_DIR/align/${file}/${file}_ada1.sorted.bam.bai;
## align ada2
bwa mem -t 5 -M -R '@RG\tID:${file}_ada2' /mnt/storage/home/psbelokopytova/insulatory_index/bds_pipeline_genome_data/hg38/bwa_index/GRCh38_no_alt_analysis_set_GCA_000001405.15.fasta $WORK_DIR/cutadapt/${file}_ada2.fq | samtools view -bS -@ 5 | samtools sort > $WORK_DIR/align/${file}/${file}_ada2.sorted.bam;
samtools index $WORK_DIR/align/${file}/${file}_ada2.sorted.bam > $WORK_DIR/align/${file}/${file}_ada2.sorted.bam.bai;
## merge files
samtools merge $WORK_DIR/align/${file}/${file}_ada1_ada2.bam $WORK_DIR/align/${file}/${file}_ada1.sorted.bam $WORK_DIR/align/${file}/${file}_ada2.sorted.bam;
samtools index $WORK_DIR/align/${file}/${file}_ada1_ada2.bam > $WORK_DIR/align/${file}/${file}_ada1_ada2.bam.bai;
## align paired reads
bwa mem -t 5 -M /mnt/storage/home/psbelokopytova/insulatory_index/bds_pipeline_genome_data/hg38/bwa_index/GRCh38_no_alt_analysis_set_GCA_000001405.15.fasta $WORK_DIR/cutadapt/${file}_1.fq $WORK_DIR/cutadapt/${file}_2.fq | samtools view -bS -@ 5 | samtools sort > $WORK_DIR/align/${file}/${file}.sorted.bam
samtools index $WORK_DIR/align/${file}/${file}.sorted.bam > $WORK_DIR/align/${file}/${file}.sorted.bam.bai
## create coverage file
~/programms/bedtools2/bin/bedtools genomecov -ibam $WORK_DIR/align/${file}/${file}.sorted.bam -bg > $WORK_DIR/align/${file}/${file}.bedgraph
## create sam
samtools view $WORK_DIR/align/${file}/${file}.sorted.bam > $WORK_DIR/align/${file}/${file}.sorted.sam
done
