#!/usr/bin/perl

use strict;

my @files = glob( "/Net/mus/data/LORRAINE/ALP/chr4.ped");
foreach my $fil ( @files ) {

  my $geno;
  my $genoc;
  my $info;

  open(FILE, $fil) || die "Could not open $fil\n";
  while(<FILE>) {
    chomp;
    my ( $a,$id,$c, $d, $p,$f,@a) = split(/\s+/);
    $info->{$id} = [0, $id, 0, 0, 0, $p] if ( $p ne "NA");
    print "$id $p, $#a\n";
    my $g;
    for( my $k=0, my $m=0;$k<$#a;$k+=2,$m++) {
      if ( $a[$k] eq "NA" || $a[$k+1] eq "NA" ) {
	$g = "0";
      }
      else {
        $g = $a[$k] . $a[$k+1];
        $genoc->[$m]{$g}++;
      }
      $geno->{$id}[$m] = $g;
      }
  }
  
  my $code;
  for(my $m=0;$m<=$#$genoc;$m++) {
    my @g = sort keys( %{$genoc->[$m]} );
    my $n=0;
    print "$m @g\n";
    foreach my $g ( @g ) {
      my @a = split( //, $g );
      if ( $a[0] ne $a[1] ) {
        $code->[$m]{$g} = 1;
      }
      else {
	$code->[$m]{$g} = $n;
        $n = 2;
      }
     print "$m $g $a[0] $a[1] $code->[$m]{$g}\n";
    }
    $code->[$m]{"0"} = 0;
  }

  my $outfile = $fil;
  $outfile =~ s/data$/num/;
  print "$outfile\n";
  open(OUTFILE, ">$outfile") || die "Could not open $outfile\n"; 
  foreach my $id ( sort keys %$geno ) {
    if ( exists( $info->{$id} ) ) {
      print OUTFILE join( " " , @{$info->{$id}});
      for(my $m=0;$m<=$#$genoc;$m++) {
	print OUTFILE " $code->[$m]{$geno->{$id}[$m]}";
      }
      print OUTFILE "\n";
    }
  }	
  print "$outfile\n";
  close(OUTFILE);
}
  

