#!/usr/bin/perl
use strict;
my $markers = [];
my $genos = {};

my $build = "build34";
my $date = "09052005";
my $gdir = "/projects/rmott/ILLUMINA/BUILD34/GENOTYPES/";
my $mapfile = "/home/rmott/public_html/MOUSE/INBREDS/build34.map.txt";

open(MAP, $mapfile ) || die "could not open $mapfile\n";
my $map;
while(<MAP>) {
	chomp;
	my ( $chr, $pos, $snp ) = split;
	$chr =~ s/chr//;
	$map->{$snp} = [$chr, $pos];
}
for( my $c=1;$c<=21; $c++ ){ 
	
	my $d = "chr$c";
	$d = "chrX" if ( $c == 20 );
	$d = "random" if ( $c == 21 );
	
	my $datafile =    "$gdir/Contributed.$d.$build.$date.data";
	my $allelesfile = "$gdir/Contributed.$d.$build.$date.alleles";
	warn "$d $datafile, $allelesfile\n";
	GetGenos( $datafile, $allelesfile, $markers, $genos );
}


my @strains = sort keys %$genos;
my $k = 0;
while( $k <= $#strains ) {
	my $outfile = "/home/rmott/public_html/MOUSE/INBREDS/GENOTYPES/BUILD34/Strains-$k.$date.txt";
	WriteRobData( $markers, $genos, \@strains, $map, $k, 200, $outfile );
	$k +=200;
}

sub WriteRobData {

	my ( $markers, $genos, $strains, $map, $from, $N, $outfile ) = @_;
	warn "outfile $outfile\n";
	if  ( open( OUT, ">$outfile" ) ){
		warn "Writing $outfile\n";
		print OUT "SNP CHR POSITION";
		for( my $j=$k; $j<$N+$k && $j <=$#$strains; $j++ ) {
			print OUT " $strains->[$j]";
		}
		print OUT "\n";
	
		foreach my $marker ( @$markers ) {
			print OUT "$marker $map->{$marker}[0] $map->{$marker}[1]";
			for( my $j=$k; $j<$N+$k && $j <= $#$strains; $j++ ) {
				print OUT " $genos->{$strains->[$j]}{$marker}";
			}
			print OUT "\n";
		}
		warn "wrote $outfile\n";
		close(OUT)
	}
}



sub GetGenos{
	my  ($datafile, $allelesfile, $markers, $genos ) = @_;
	
	my @mark;
	if ( open(ALLELES, $allelesfile ) ) {
		while(<ALLELES>) {
			push @mark, $1 if ( /^marker\s+(\S+)/ );
		}
		close(ALLELES);
	}
	else {
		die "Could not open $allelesfile\n";
	}
	if (open(DATA, $datafile ) ) {
		warn "reading $datafile\n";
		while(<DATA>) {
			my ( $fam, $id, $mum, $dad, $sex,  $ph, @g ) = split;
#			warn "$id\n";
			for(my $k=0;$k<$#g;$k+=2) {
				my ( $a1, $a2 ) = ($g[$k], $g[$k+1]);
				if ( $a1 eq $a2 && $a1 ne "NA" ) {
					$genos->{$id}{$mark[$k/2]} = $a1;
				}
				elsif ( $a1 ne $a2 && $a1 ne "NA" && $a2 ne "NA" ) {
					$genos->{$id}{$mark[$k/2]} = "H";
				}
				else
				{
					$genos->{$id}{$mark[$k/2]} = "U";
				}
			}
		}
		close(DATA);
	}
	else {
		die "Could not open $datafile\n";
	}
	push @$markers, @mark;

}
