#!/usr/bin/perl -w 
#Sample Random Path output
#This will take as input HAPMIX 6 column file using 38:2 option and create 
#a) 4 phased EIGENSTRAT files: 2 for local ancestry at each chromosome, and 2 for genotypes
#b) A local ancestry EIGENSTRAT fileby adding columns for local ancsy for Haploid 1 and 2

$DIR = $ARGV[0];
$NADMIX = $ARGV[1];
$CHR = $ARGV[2];
$mode = $ARGV[3];
$admixpop = $ARGV[4];

for($n=0;$n<$NADMIX;$n++)
  {
    open(ANCFILE,"$DIR/$admixpop.SAMPRANPATH.$n.$CHR") ||die("COF");

    @row = <ANCFILE>;
    $nsnps = scalar @row;
    for($i = 0; $i < scalar @row; $i++)
      {
	chomp($row[$i]);
	@data = split(' ',$row[$i]);
	$key=$n.":".$i;
	if(scalar @data == 6)
	  {
	    $data[0] = 1 - $data[0];
	    $data[3] = 1-$data[3];
 
	    if($mode eq 'ANC_INT_SAMPLED')
	      {
		$totlocalanc{$key} = $data[0]+$data[3];
	      }
	    elsif($mode eq 'HAPLOID_FILES')
	      {
		$localanc1{$key} = $data[0];
		$geno1{$key} = $data[2];
		$localanc2{$key} = $data[3];
		$geno2{$key} = $data[5];
	      }
		
	  }
	elsif(scalar @data ==7)
	  {
	    $data[1] = 1 - $data[1];
	    $data[4] = 1-$data[4];
	    if($mode eq 'ANC_INT_SAMPLED')
	      {
		$totlocalanc{$key} = $data[1]+$data[4];
	      }
	    elsif($mode eq 'HAPLOID_FILES')
	      {
		$localanc1{$key} = $data[1];
		$geno1{$key} = $data[3];
		$localanc2{$key} = $data[4];
		$geno2{$key} = $data[6];
	      }
	  }
      }
    close ANCFILE;
  }


if($mode eq 'ANC_INT_SAMPLED')
  {
    open(EIGENANCFILE,">$DIR/$admixpop.SAMPRANPATH.ANCINTSAMP.$CHR") || die("COF");
  }
elsif($mode eq 'HAPLOID_FILES')
  {
    open(EIGENANCH1FILE,">$DIR/$admixpop.SAMPRANPATH.ANCHAP1.$CHR") || die("COF");
    open(EIGENANCH2FILE,">$DIR/$admixpop.SAMPRANPATH.ANCHAP2.$CHR") || die("COF");
    open(EIGENGENOH1FILE,">$DIR/$admixpop.SAMPRANPATH.GENOHAP1.$CHR") || die("COF");
    open(EIGENGENOH2FILE,">$DIR/$admixpop.SAMPRANPATH.GENOHAP2.$CHR") || die("COF");
  }
    
for($j = 0; $j < $nsnps;$j++)
  {
    for($k=0;$k<$NADMIX;$k++)
      {
	$key = $k.":".$j;
	if($mode eq 'ANC_INT_SAMPLED')
	  {
	    print EIGENANCFILE $totlocalanc{$key};
	  }
	elsif($mode eq 'HAPLOID_FILES')
	  {  
	    print EIGENANCH1FILE $localanc1{$key};
	    print EIGENANCH2FILE $localanc2{$key};
	    print EIGENGENOH1FILE $geno1{$key};
	    print EIGENGENOH2FILE $geno2{$key};
	  }
      }
    if($mode eq 'ANC_INT_SAMPLED')
      {
	print EIGENANCFILE "\n";
      }
    elsif($mode eq 'HAPLOID_FILES')
      {
	print EIGENANCH1FILE "\n";
	print EIGENANCH2FILE "\n";
	print EIGENGENOH1FILE "\n";
	print EIGENGENOH2FILE "\n";
      }
  }

