#!/usr/bin/perl

# This script was originally written by Terry and was copied from
# /cluster/bin/scripts/createSTSbed into the kent/src tree in order
# to get it under CVS control, and modified to make stsMapRat instead 
# of human stsMap; added warnings & strict.

# $Id: createStsMapRat,v 1.3 2006/06/15 20:45:32 angie Exp $

use warnings;
use strict;

# File: createSTSbed
# Author: Terry Furey
# Date: 10/2001
# Description: Creates bed file to be loaded into database for STS track

# Usage message
if ($#ARGV != 1) {
  print STDERR "USAGE: createStsMapRat <stsInfoRat.tab> <stsMarkers_pos.rdb>\n";
  exit(1);
}

# Read in parameters
my $info = shift(@ARGV);
open(INFO, "<$info") || die("Could not open $info\n");
my $pos = shift(@ARGV);
open(POS, "<$pos") || die("Could not open $pos\n");

# Read in and record STS placement info
my %chr;
my %start;
my %end;
my %acc;
my %oacc;
my %score;
my $line = <POS>;
$line = <POS>;
while ($line = <POS>) {
  chomp($line);
  my ($chr, $start, $end, $id, $place, $acc, $oacc) = split("\t",$line);
  if ($place <= 3) {
    if ($start{$id}) {
      $chr{$id} .= ",$chr";
      $start{$id} .= ",$start";
      $end{$id} .= ",$end";
      $acc{$id} .= ",$acc";
      $oacc{$id} .= ",$oacc";
    } else {
      $chr{$id} = $chr;
      $start{$id} = $start;
      $end{$id} = $end;
      $acc{$id} = $acc;
      $oacc{$id} = $oacc;
    }
    if ($place == 1) {
      $score{$id} = 1000;
    } else {
      $score{$id} = int(1500/$place);
    }
  }
}
close(POS);

# Read in STS info file and print out bed file
while ($line = <INFO>) {
  chomp($line);
  my @fields = split("\t",$line);
  my $id = $fields[0];
  if ($chr{$id}) {
    my @chrs = split(",",$chr{$id});
    my @starts = split(",",$start{$id});
    my @ends = split(",",$end{$id});
    my @accs = split(",",$acc{$id});
    my @oaccs = split(",",$oacc{$id});
    for (my $i = 0; $i <= $#starts; $i++) {
      print "$chrs[$i]\t$starts[$i]\t$ends[$i]\t$fields[1]\t$score{$id}\t$id\t$accs[$i]\t$oaccs[$i]\t";
      # RH
      if ($fields[19]) {
	print "$fields[19]\t$fields[20]\t$fields[21]\t";
      } else {
	print "\t0.00\t0.0\t";
      }
      # FHH
      if ($fields[13]) {
	print "$fields[13]\t$fields[14]\t";
      } else {
	print "\t0.00\t";
      }
      # SHRSP
      if ($fields[16]) {
	print "$fields[16]\t$fields[17]\n";
      } else {
	print "\t0.00\n";
      }
    }
  }
}
close(INFO);
