
#!/usr/bin/perl

use strict;


my @chrs = ('X', 'Y');
print("@chrs\n");


my @indices_males = (0..9, 12, 13, 19, 22..26, 28);
my @indices_females = (0..8, 10..11, 14..18, 20..21, 27);
print("@indices_males\n@indices_females\n");


my ($line, $start, $line_males, $line_females);
my (@row, @row_males, @row_females);


foreach my $ch ( @chrs ) {

    print("chromosome $ch\n");

    my $wm_fname = join('', 'vcf/SNPs.filtered.chr', $ch,'.vcf');
    print("input file $wm_fname\n");

    my $mfile = join('', 'vcf/SNPs.filtered.males.chr', $ch, '.vcf');
    my $ffile = join('', 'vcf/SNPs.filtered.females.chr', $ch, '.vcf');


    open(OUTM, '>', $mfile) or die "Cannot open file $mfile for writing, reason $!\n ";
    open(OUTF, '>', $ffile) or die "Cannot open file $ffile for writing, reason $!\n ";

    open(INW, '<', $wm_fname) or die "Cannot open vcf file $wm_fname, reason $!\n";

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

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

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

    my $header_line = $line;
    chomp($header_line);
    my @header = split("\t", $header_line);

    my @males_header = @header[@indices_males];
    my @females_header = @header[@indices_females];
    my $males_header_line = join("\t", @males_header);
    my $females_header_line = join("\t", @females_header);
    print(OUTM "$males_header_line\n");
    print(OUTF "$females_header_line\n");


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

	chomp($line);
        @row = split("\t", $line);

	@row_males = @row[@indices_males];
	@row_females = @row[@indices_females];
	$line_males = join("\t", @row_males);
	$line_females = join("\t", @row_females);

	print(OUTM "$line_males\n");
	print(OUTF "$line_females\n");
    }
    close(INW);

    close(OUTM);
    close(OUTF);

} # end of chr loop
