#!/bin/awk -f

# An awk script for combining complementary CpGs.
# Usage: [path]/combineCompleCpGs.sh input

# Input format: extended COVERAGE file generated by "addSC.r", hence 8-column tab-delimited;
#	column 7 should only contain "+" and "-";
#	the file should be sorted by coordinate.

# Output: to stdout;
#	the same format as input;
#	combined CpGs will have a strand information of "*";
#	uncombined "-" CpGs' positions will be adjusted 1bp upstream.

BEGIN{
	FS="\t";
	OFS="\t";
	pos=0
}

$7=="+"{
	if(pos!=0)print a;
	a=$0;
	sca=$1;
	pos=$2;
	next;
}

$7=="-"{
	if(pos==0)
	{
		$2=$2-1;
		$3=$3-1;
		print;
	}
	else
	{
		if(($1!=sca)||($2>(pos+1)))
		{
			print a;
			$2=$2-1;
			$3=$3-1;
			print;
		}
		else
		{
			split(a,b1,"\t");
			split($0,b2,"\t");
			m=b1[5]+b2[5];
			u=b1[6]+b2[6];
			print sca,pos,pos,m/(m+u)*100,m,u,"*","CpG"
		}
		pos=0;
	}
}
