#!/usr/bin/perl
use strict;

my $vdir = "/data/mus/inbreds_var/latest";
my $indels = "20100528-indels.vcf";

my $ifile = "$vdir/$indels";
open(VCF,$ifile) || die "Could not open $ifile\n";
my @head = ( "129P2", "129S5", "AKR", "C3H", "CAST", "DBA", "NOD", "PWK", "WSB", "129S1", "A_J", "BALB", "C57BL", "CBA", "LP_J", "NZO", "SPRET"); 	

my @cc = ( "A_J", "C57", "129S1", "NOD", "NZO", "CAST", "PWK", "WSB" );
my @ccpublic = ( "A/J", "C57BL/6J", "129S1SvImJ", "NOD/LtJ", "NZO/HILtJ", "CAST/EiJ", "PWK/PhJ", "WSB/EiJ");

my @hs = ( "A_J", "AKR", "BALB", "C3H", "C57", "CBA", "DBA", "LP_J" );
my @hspublic =  ("A.J", "AKR.J", "BALB.cJ", "C3H.HeJ", "C57BL.6J", "CBA.J", "DBA.2J", "LP.J");

my $idx;
my $n=1;
foreach my $h ( @head ) {
  $idx->{$h} = $n;
  $n++;
  print "$h $n\n";
}
$idx->{"C57"} = 0;
my $last;

foreach my $c ( @cc ) {
  print "CC $c $idx->{$c}\n";
}

foreach my $c ( @hs ) {
  print "HS $c $idx->{$c}\n";
}

my $last;
my $n;

while(<VCF>) {
  chomp;
  if ( ! /^\#/ ) {
    my ( $chrom, $pos, $ID, $REF, $ALT, $QUAL, $FILTER, $INFO, $FORMAT, @a ) = split;

    if ( $chrom ne $last ) {
      close(CC);
      close(HS);
      open(CC, ">chr$chrom.CC.txt") || die "Could not open chr$chrom.CC.txt\n";
      print CC join( "\t", "chr", "bp", @ccpublic ) . "\n";
      open(HS, ">chr$chrom.HS.txt") || die "Could not open chr$chrom.HS.txt\n";
      print HS join( "\t", "chr", "bp", @hspublic ) . "\n";
      print "new chrom $chrom\n";
    }
    $last = $chrom;
    print "$chrom $n\n" if ( !($n++ % 100000));
    
    my @b = ("0/0");
    foreach my $a ( @a ) {
      my $y = "0/0";
      if ( $a ne "." ) {
	($y) = $a =~ /^([^\:]+)/;
      }
      push @b, $y;
    }
    
    print join(" ", @b) . "\n" if ( $n<100);
    my $ccal;
    my @c;
    foreach my $x ( @cc ) {
      my $y = $b[$idx->{$x}];
      push @c, $y;
      $ccal->{$y}++;
    }	
    my @k = keys %$ccal;
    
    print CC join( "\t", $chrom, $pos, @c ) . "\n" if ( $#k >= 1 );
    
    
    my $hsal;
    my @c;
    foreach my $x ( @hs ) {
      my $y = $b[$idx->{$x}];
      push @c, $y;
      $hsal->{$y}++;
    }	
    my @k = keys %$hsal;
    
    print HS join( "\t", $chrom, $pos, @c ) . "\n" if ( $#k >= 1 );
  }
}
close(CC);
close(HS);  
  
