#!/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 @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 @snpfiles = glob("mouse*.tab");
foreach my $snpfile (@snpfiles) {

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"} = 3;
my $last;

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

foreach my $c ( @hs ) {
  print "HS $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 ($id,$chrom, $bp, $ref ) = ($a[0],$a[1],$a[2],$a[3]);
  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 "chrom $chrom\n";
  }
  print "$chrom $n\n" if ( !($n++ % 100000));

  my($r,$a) = $ref =~ /^(.)\/(.)/;
  $ref = $r;
  $last = $chrom;
  $code->{"C57"} = $ref;
  my $ccal;
  my @c;
  foreach my $x ( @cc ) {
    my $y = $code->{$a[$idx->{$x}]};
    $y = $x if (($y eq "N") || (!$y));
    $y = $ref if ( $x eq "C57");
    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}]};
    $y = $x if (($y eq "N") || (!$y));
    $y = $ref if ( $x eq "C57");
    push @c, $y;
    $hsal->{$y}++;
  }	
  my @k = keys %$hsal;

  print HS 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
}
