#!/usr/bin/perl

use strict;

open( CONVERT, "/Net/spud/raid/GSCAN/ARABIDOPSIS/hsril2magic.txt") || die "No conversion file hsril2magic.txt\n";
my $magic;
while(<CONVERT>) {
  chomp;
  my ( $a, $b) = split;
  $magic->{$a} = $b;
}

my $geno;
my $map;
my $coord;
my $issnp;
my $orig;

foreach my $fil ( glob("*.csv")) {
  open(FIL,$fil) || die "Could not open $fil\n";

  my ($chr) = $fil =~ /(\d+)/;
  my $head = <FIL>;
  chomp($head);
  $head =~ s/_/-/g;
  my ($x, @snp) = split(/,/, $head);
  for( my $k=0;$k<=$#snp;$k++) {
    $issnp->{$snp[$k]} ++;
  }
	
  while(<FIL>) {
    chomp;
    s/ND/NA/g;
    s/\-\-/NA/g;
    my ( $id, @g ) = split(/,/);

    if ( $#g != $#snp ) {
      print "ERROR $id $#g != $#snp \n";
    }
    my $fam = $id;
    if ( $id =~ /(\d+)_S/ ) {
      $id = "HSRIL.$1";
    }
    if ( $id =~ /HSRIL[^\d]*(\d+)/ ) {
      $id = "HSRIL.$1";
    }
    
    if ( $magic->{$id} ) {
      $fam = $magic->{$id};
    }	
    $orig->{$id} = $fam;
    for( my $k=0;$k<=$#g;$k++) {
      $geno->{$id}{$snp[$k]} =  " $g[$k] $g[$k]";
      $issnp->{$snp[$k]} ++;
    }
  }

}

my @ids = sort keys %$geno;

my $e=0;
for( my $c=1;$c<=5;$c++) {
#  my $allelesfile = "/raid/ARABIDOPSIS/GENOTYPES/11092008/chr$c.HSRIL.clean.alleles";
  my $allelesfile = "chr$c.MAGIC.alleles";
  open(ALLELESFILE, $allelesfile) || die "Could not open $allelesfile\n";
  $_ = <ALLELESFILE>;
  while(<ALLELESFILE>) {
    chomp;
    if ( /^marker\s+/) {
      my ($dummy, $snp, $na, $chr, $cm ) = split;
      $snp =~ s/_/-/g;
      push @{$map->{$c}}, $snp;
      $coord->{$c}{$snp} = $cm;
      if ( ! $issnp->{$snp} ) {
	$e++;
	print "$e ERROR $snp missing\n";
      }
    }
  }
  my $pedfile = "chr$c.MAGIC.data";
  open(PED, ">$pedfile") || die "Could not open $pedfile\n";
  foreach my $id ( @ids ) {
    if ( 1 ) { #$id =~ /MAGIC/ ) {
      print PED "$orig->{$id} $id 0 0 NA NA";
      foreach my $snp ( @{$map->{$c}} ) {
	print PED $geno->{$id}{$snp};
      }
      print PED "\n";
    }
  }
}

