#!/usr/bin/perl

use strict;


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 @f2 = ( "BALB", "129S1", "C57");
my @f2public = ("BALB", "129S1", "C57");

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 $snpfile = "/data/mus/martin/strains/020310download/20100301-isec2-callable-nonhets.tab";
open(SNPS,$snpfile) || die "Could not open $snpfile\n";
my $head = <SNPS>;
print $head;
chomp($head);
my @header = split(/\s+/, $head);
my $idx;
my $n=0;
foreach my $h ( @header ) {
  $idx->{$h} = $n++;
  print "$h $n\n";
}
$idx->{"C57"} = 2;
my $last;

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

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

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

my $code = { "AA"=>"A", "CC"=>"C", "GG"=>"G", "TT"=>"T", "A"=>"A", "C"=>"C", "G"=>"G", "T"=>"T" };
my $n=0;
while(<SNPS>) {

  chomp;
  my  @a = split;
  my ($chrom, $bp, $ref ) = ($a[0],$a[1],$a[2]);
  if ( $chrom ne $last ) {
    close(CC);
    close(HS);
    close(F2);
    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";
    open(F2, ">chr$chrom.F2.txt") || die "Could not open chr$chrom.F2.txt\n";
    print F2 join( "\t", "chr", "bp", @f2public ) . "\n";


    print "chrom $chrom\n";
  }
  print "$chrom $n\n" if ( !($n++ % 100000));

  $last = $chrom;
  $code->{".."} = $ref;
  my $ccal;
  my @c;
  foreach my $x ( @cc ) {
    my $y = $code->{$a[$idx->{$x}]};
    push @c, $y;
    $ccal->{$y}++;
  }	
  my @k = keys %$ccal;
  
  print CC join( "\t", $chrom, $bp, @c ) . "\n" if ( $#k >= 1 );


  my $hsal;
  my @c;
  foreach my $x ( @hs ) {
    my $y = $code->{$a[$idx->{$x}]};
    push @c, $y;
    $hsal->{$y}++;
  }	
  my @k = keys %$hsal;

  print HS join( "\t", $chrom, $bp, @c ) . "\n" if ( $#k >= 1 );

  my $f2al;
  my @c;
  foreach my $x ( @f2 ) {
    my $y = $code->{$a[$idx->{$x}]};
    push @c, $y;
    $f2al->{$y}++;
  }	
  my @k = keys %$f2al;

  print F2 join( "\t", $chrom, $bp, @c ) . "\n" if ( $#k >= 1 );

}



#CHROM	POS	REF	129P2	129S1	129S5	AKR	A_J	BALB	C3H	C57BL	CAST	CBA	DBA	LP_J	NOD	NZO	PWK	SPRET	WSB
