#!/bin/sh
#
# Script name: ScriptE_bam_to_methylKit.sh
#
# Purpose of script: To prepare a methylKit data format from a bam file
#
# Date Created: 2022/8/25
#
# 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_xxxxxbases.bam &


export PATH=/path/to/Bismark-0.22.3/:$PATH

# Please refer to the following website to prepare the Bisulfite_Genome for hisat2
# https://felixkrueger.github.io/Bismark/options/genome_preparation/
genome=/path/to/the/directory/containing/Bisulfite_Genome

target=` echo $1 | sed 's/.bam//' `

bismark_methylation_extractor -p --bedGraph --comprehensive --merge_non_CpG --multicore 8 $1
coverage2cytosine --coverage_threshold 1 --genome_folder $genome ${target}.bismark.cov.gz -o $target


echo -e "chrBase\\tchr\\tbase\\tstrand\\tcoverage\\tfreqC\\tfreqT" > ${target}_methylKit.txt
cat ${target}.CpG_report.txt | \
awk 'BEGIN{OFS="\t"}$3=="+"{print $1"."$2,$1,$2,"F",$4+$5,100*$4/($4+$5),100*$5/($4+$5)}$3=="-"{print $1"."$2,$1,$2,"R",$4+$5,100*$4/($4+$5),100*$5/($4+$5)}' | \
sort -V -k2,2 -k3,3 >> ${target}_methylKit.txt

exit
