#!/bin/sh
#
# Script name: prep_bam_files_3776Mb.sh
#
# Purpose of script: To prepare bam files containing almost the same base number
#
# Date Created: 2022/8/18
#
# Written by Keita Hasegawa and Kazuhiko Nakabayashi for the following study:
#
# Keita Hasegawa et al.
# "A capture methyl-seq protocol with improved efficiency and cost-effectiveness using pre-pooling and enzymatic conversion"
# 
#
# Contact information:
# Kazuhiko Nakabayashi, Ph.D.
# nakabaya-k@ncchd.go.jp
# Laboratory of Developmental Genomics, Research Institute, National Center for Child Health and Development, Tokyo, Japan
#
# Usage:
# ./this_script.sh target_name_sort.bam total_base_required read_length

echo "tarrget_bam:" $1 | tee results.txt
echo "total_base: " $2 | tee -a results.txt
echo "read_length:" $3 | tee -a results.txt
echo ""  | tee -a results.txt

target_base=$2
read_length=$3
input_read_number=` echo $2 | awk -v read_length="$read_length" '{print int(int($1/read_length)*1.2)}' `

echo "input_reads:" $input_read_number  | tee -a results.txt
echo ""  | tee -a results.txt

print_interval=` echo $input_read_number | awk '{print int($1/20)}' `

samtools view $1 | head -$input_read_number | cut -f1,6 | sed 's/M/M\t/g' | sed 's/I/I\t/g' | sed 's/D/D\t/g' | \
awk -v OFS="\t" '{for(i=2;i<=NF;i++){if($i~/M/)print $1,$i}}' | sed 's/M//' | \
awk -v OFS="\t" -v target_base="$target_base" -v interval="$print_interval" \
'\
total<target_base{total+=$2; linename=$1; linenum++}
(total<target_base)&&(NR%interval==0){print NR,$1,total}\
total>target_base&&NR%interval==0{print NR}\
END{print linenum,linename,total}\
' | tee -a results.txt

readID=` tail -1 results.txt | cut -f2 `
echo ""  | tee -a results.txt
echo "final_readID:" $readID  | tee -a results.txt
echo ""  | tee -a results.txt
echo "positions_in_the_target_bam: $1" | tee -a results.txt
samtools view $1 | head -$input_read_number | cut -f1 | cat -n | grep $readID | tee -a results.txt
echo ""  | tee -a results.txt
echo "done" | tee -a results.txt

exit
