#!/usr/bin/perl
=head2 SYNOPSIS

	Description: Extract the methylation info from the bismark result files (C*context_prefix.txt.gz)
             
=head2 AUTHOR

	Kang Zhang  Email:  demut@foxmail.com
	
=cut


my $suffix=$ARGV[0] or die "Pls provide the suffix of inputs. <Such as :_context_test.txt.gz>\n";

my @info=("CpG","CHG","CHH");

foreach my $type (@info){
	print STDERR "Processing $type...\n";
	undef %count; undef %countAll;
	my $fileRaw=$type.$suffix;
	my $file=$fileRaw;
	$file=~s/\.gz$//;
	system ("gunzip -c $fileRaw > $file") if ( ! -e $file);
	my $file_out=$file.".result";
	if(-e $file_out){print STDERR "Have found the result: $file_out! Skip it !\n";next;}
	open IN,"<$file" or die;
	while(<IN>){
		next if (/^Bismark/);
		my @arr=split;
		$countAll{$arr[2]}{$arr[3]}++;
		if(/\s+\+\s+/){
			$count{$arr[2]}{$arr[3]}++;
		}
	}
	close IN;
	open OUT,">$file_out";
	print OUT "<Chr>\t<Position>\t<Total_Read_Count>\t<Methylated_Read_Count>\n";
	foreach my $chr (sort keys %countAll){
		foreach my $pos (sort {$a <=> $b} keys %{$countAll{$chr}}){
			if(! defined $count{$chr}{$pos}){
				$count{$chr}{$pos}=0;
			}
			print OUT "$chr\t$pos\t$countAll{$chr}{$pos}\t$count{$chr}{$pos}\n";
		}
	}
	close OUT;
	print STDERR "-----> Finished.\n";
}
