#!/usr/bin/perl
#
use strict;
use Getopt::Std;

my $input = shift;
read_phase_output($input);

sub read_phase_output
{
	my $phase_output = shift;
	warn("reading $phase_output\n");
	my ($output, $ind_num, $loci_num, $best_pairs, @genotypes, @haplotype);

	open FH, $phase_output or die "$!: $phase_output\n";
	{
		local $/;
		$output = <FH>;
	}
	close FH;

	($ind_num, $loci_num) = $output =~ /Number of Individuals: (\d+)\nNumber of Loci: (\d+)\n/;
	($best_pairs) = $output =~ /BEGIN BESTPAIRS1\n(.*)END BESTPAIRS1\n/s;
	@genotypes = $best_pairs =~ /\d #(\S+\n\D+)\n/g;
	if (@genotypes != $ind_num) {
		warn("unequal individual number\n");
		die;
	}

	for (my $i=0; $i<$ind_num; $i++) {
		my ($gtype, $name, $hap1, $hap2, @a1, @a2, @g);

		$gtype = shift @genotypes;
		($name, $hap1, $hap2) = split /\n/, $gtype;
		$hap1 =~ s/[^\w]//g;
		$hap2 =~ s/[^\w]//g;
		if (length($hap1) != length($hap2) or length($hap1) != $loci_num) {
			warn("unequal loci number: $name\n");
			die;
		} else {
			print ">$name\n";
			print $hap1, "\n";
			print ">$name.2\n";
			print $hap2, "\n";
		}
	}

	warn("done\n");
}
