#!/usr/bin/perl -W
# File: calcFlipSnpPos
# Author: Daryl Thomas
# Date: 3/2002; 5/2002; 9/2004
# Description: Calculate SNP positions in flipped contigs

if ($#ARGV < 2) { die "USAGE: calcFlipSnpPos seq_contig.md gp.ncbi.b29 gp.ncbi.b29.flipped\n"; }
$contigFile       = $ARGV[0];
$buildFile        = $ARGV[1];
$flippedBuildFile = $ARGV[2];
if ($#ARGV >=3 ) { $format = $ARGV[3];} else {$format="default";}

open(CFILE, "<$contigFile")       || die("Could not open $contigFile\n");
open(BFILE, "<$buildFile")        || die("Could not open $buildFile\n");
open(FFILE, ">$flippedBuildFile") || die("Could not open $flippedBuildFile\n");
%contigLen = ();

# Process each line in the seq_contig.md file
# which lists the contigs and orientations in the build
while(<CFILE>) 
{
    chomp;
    ($build, $thischr, $start, $end, $orien, $thisctg, $foo) = split "\t", $_, 7;
    next if ($orien ne "-");
    ($ctg, $ver)    = split /\./, $thisctg;
    $contigLen{$ctg} = $end - $start + 1;
}

if ($format eq "bed")
{
    while(<BFILE>) 
    {
	chomp;
	($thisChrCtg, $oldStart, $oldEnd, $remainder) = split "\t", $_, 4;
	($chr, $thisCtg) = split /\//, $thisChrCtg;
	($ctg, $ver)     = split /\./, $thisCtg;
	if ( defined $contigLen{$ctg} )
	{
	    print STDERR;
	    $newStart = $contigLen{$ctg} - $oldStart + 1;
	    $newEnd   = $contigLen{$ctg} - $oldEnd   + 1;
	    print FFILE "$thisChrCtg\t$newStart\t$newEnd\t$remainder\n";
	}
	else { print FFILE "$_\n"; }
    }
}
else
{
    while(<BFILE>) 
    {
	chomp;
	($rsId, $type, $thisChrCtg, $oldPos, $remainder) = split "\t", $_, 5;
	($chr, $thisCtg) = split(/\//, $thisChrCtg);
	($ctg, $ver) = split(/\./, $thisCtg);
	if(defined $contigLen{$ctg})
	{
	    $newPos=$contigLen{$ctg}-$oldPos+1;
	    print FFILE "$rsId\t$type\t$thisChrCtg\t$newPos\t$remainder\n";
	}
	else { print FFILE "$_\n"; }
    }
}
