#!/bin/sh
#
# Script name: ScriptF_Cumulative_ReadDepth.sh
#
# Purpose of script: To obtain cumulative read depth data for one library
#
# Date Created: 2022/9/13
#
# 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 data_file.txt column_number 
#
# The data_file.txt needs to contain the read depth data of eight libraries (EMCap and BSCap_high in Fig.1G)
# Data for the 3147687 target CpG sites covered in at least one of the eight libraries (read depth >= 1) were subjected to this script.
# Specify a column number for each library when you run this script 
 
file=$1
col=$2

echo $file
echo $col

cat $file | cut -f${col} | \
awk '$1>0' | sort | uniq -c | awk -v OFS="\t" '{print $1,$2}' | sort -Vr -k2,2 | \
awk -v OFS="\t" '{total+=$1;print $2, total}' | sort -V -k1,1 > cumulative_counts_1_to_max_col${col}_${file}

cat cumulative_counts_1_to_max_col${col}_${file} | \
awk -v OFS="\t" 'NR==1{total=$2;print $1,$2/total}NR>=2{print $1,$2/total}' \
> cumulative_ratios_1_to_max_col${col}_${file}


# The number of ontarget CpG sites is 3156463

echo -e "0\t3156463" | cat - cumulative_counts_1_to_max_col${col}_${file} > cumulative_counts_0_to_max_col${col}_${file}

cat cumulative_counts_0_to_max_col${col}_${file} | \
awk -v OFS="\t" 'NR==1{total=$2;print $1,$2/total}NR>=2{print $1,$2/total}' \
> cumulative_ratios_0_to_max_col${col}_${file}

exit
