#!/usr/bin/perl

use strict;



my @chrs = (1..19, 'X', 'Y', 'M');
#my @chrs = (19);
print("@chrs\n");

my ($line, $ch);

foreach $ch ( @chrs ) {
    print("chromosome $ch\n");

    my $INfile = 'MegaMUGAsnps.Flines.TAUlines.chr'.$ch.'.csv';
    my $OUTfile = 'MegaMUGAsnps.clean.Flines.TAUlines.chr'.$ch.'.csv';


    open(IN, '<', $INfile) or die "Cannot open file $INfile, reason $!\n";
    open(OUT, '>', $OUTfile) or die "Cannot open map file $OUTfile for writing, reason $!\n";

    my $header_line = <IN>;
    print(OUT "$header_line");

    my ($chr, $Nsnps, $Nfclean, $ic, $Nghet, $Ngmiss, $Ngclean);
    my (@row);

    $Nsnps = 0;
    $Nfclean = 0;
    $Ngclean = 0;

    while ( defined($line = <IN>) ) {
	chomp($line);
	$Nsnps++;
	@row = split(',', $line);

	my @founders = @row[3..10];
	my $Nfhet = 0;
	my $Nfmiss = 0;
	for ( $ic=0; $ic<=$#founders; $ic++ ) {
	  if ( $founders[$ic] eq 'H' ) {
	      $Nfhet++;
	  } elsif ( $founders[$ic] eq 'N' ) {
	      $Nfmiss++;
	  }
	}
#	print("@founders  $Nfhet  $Nfmiss\n");

	if ( $Nfhet == 0 && $Nfmiss == 0 ) {
	    $Nfclean++;

	    my @genotypes = @row[11..$#row];
#	    print("@genotypes\n");
	    my $Ntgen = @genotypes;
	    if ( $Ntgen == 63 ) {

		$Nghet = 0;
		$Ngmiss = 0;
		for ( $ic=0; $ic<=$#genotypes; $ic++ ) {
		    if ( $genotypes[$ic] eq 'H' ) {
			$Nghet++;
		    } elsif ( $genotypes[$ic] eq 'N' ) {
			$Ngmiss++;
		    }
		}
#		print("Ngenotypes $Ntgen    Nhets $Nghet    Nmissing $Ngmiss\n");

	    } else {
		print("ERROR - not enough genotypes\n");
		exit;
	    }

	    if ( $Ngmiss <= 15 && $Nghet <= 15 ) {
		print(OUT "$line\n");
		$Ngclean++;
#		print("Ngenotypes $Ntgen    Nhets $Nghet    Nmissing $Ngmiss\n");
	    }

	} # if founder QC loop
    } # end of while loop

    close(OUT);
    close(IN);

    print("chr $ch Nsnps $Nsnps Nsnps_after_founderQC $Nfclean Nsnps_after_genotypeQC $Ngclean\n");

} # end of chr loop

