#!/usr/bin/perl

use strict;


my $fname = './final.vcf';

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

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

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

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

    open(OUT, '>', 'final.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;

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

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

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

    close(OUT);
    close(IN);
}



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

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

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

    open(OUT, '>', 'final.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;

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

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

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

    close(OUT);
    close(IN);
}
