#!/usr/bin/perl

use strict;


my $fname = 'vcf/genotypes.raw.filtered.hwe.recode.vcf';

my @chrs = (1..19);
#print("@chrs\n");

my ($line, $start, $ch);

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

    open(IN, '<', $fname) or die "Cannot open file $fname, reason $!\n";

    open(OUT, '>', 'vcf/genotypes.raw.filtered.chr'.$ch.'.vcf') or die "Cannot open file for writing, reason $!\n";

    my $line = <IN>;
    my $start = substr( $line, 0, 2);

    while ( $start eq '##' ) {
	print(OUT "$line");

	$line = <IN>;
	$start = substr( $line, 0, 2);
    } # end of headers while loop

    my $header_line = $line;
    print(OUT "$header_line");

    my $chr;
    my @row;

    my $Ntotal = 0;

    while ( defined($line = <IN>) ) {

	@row = split(/\t/, $line);
	$chr = substr($row[0], 3);

	if ( $chr == $ch ) {
	    $Ntotal = ( $Ntotal + 1 );
	    print( OUT "$line");
	} # end of chr if loop
    } # end of while loop

    close(OUT);
    close(IN);

    print("Chromosome $ch: total SNPs $Ntotal\n");
} # end of chr loop

my @chrs = ('X', 'Y');

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

    open(IN, '<', $fname) or die "Cannot open file $fname, reason $!\n";

    open(OUT, '>', 'vcf/genotypes.raw.filtered.chr'.$ch.'.vcf') or die "Cannot open file for writing, reason $!\n";

    my $line = <IN>;
    my $start = substr( $line, 0, 2);

    while ( $start eq '##' ) {
        print(OUT "$line");

        $line = <IN>;
        $start = substr( $line, 0, 2);
    } # end of headers while loop                                                                                       

    my $header_line = $line;
    print(OUT "$header_line");

    my $chr;
    my @row;

    my $Ntotal = 0;

    while ( defined($line = <IN>) ) {

        @row = split(/\t/, $line);
        $chr = substr($row[0], 3);

        if ( $chr eq $ch ) {
	    $Ntotal = ( $Ntotal + 1 );
            print( OUT "$line");
        } # end of chr if loop                                                                                          
    } # end of while loop                                                                                               

    close(OUT);
    close(IN);

    print("Chromosome $ch: total SNPs $Ntotal\n");
}
