#!/usr/bin/perl

use strict;


my @chrs;
#my @chrs = (1..19);
my @Achrs = ('X', 'Y', 'M');

my @mice = (101, 211, 218, 227, 231, 234, 236, 246, 303, 310, 311, 313, 314, 327, 329, 330, 334, 34, 44, 54);


foreach my $mouse ( @mice ) {
    print("mouse $mouse\n");

    my $fname = join('', '/data/mus/xiang/align_wildmus/wildmus', $mouse, '/mcmerge/wildmus', $mouse, '.imrdenom.sdi');

    my ($line, $ch, $chr, $len, $ref);
    my (@row);

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

	my $sfile = join('', 'SNPs/indiv/wildmus', $mouse, '.imrdenom.snps.chr', $ch, '.sdi');
	my $ifile = join('', 'INDELs/wildmus', $mouse, '.imrdenom.indels.chr', $ch, '.sdi');


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

	open(OUS, '>', $sfile) or die "Cannot open file $sfile for writing, reason $!\n";
	open(OUI, '>', $ifile) or die "Cannot open file $ifile for writing, reason $!\n";


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

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

	    if ( $chr == $ch ) {

		$len = $row[2];
		$ref = $row[3];
		if ( $len == 0 && length($ref) == 1 ) {
		    print(OUS "$line\n");
		} else {
		    print(OUI "$line\n");
		}
	    } # end of chr if loop
	} # end of while loop

	close(OUS);
	close(OUI);
	close(IN);

    } # end of chr loop


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

	my $sfile = join('', 'SNPs/indiv/wildmus', $mouse, '.imrdenom.snps.chr', $ch, '.sdi');
	my $ifile = join('', 'INDELs/wildmus', $mouse, '.imrdenom.indels.chr', $ch, '.sdi');

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

	open(OUS, '>', $sfile) or die "Cannot open file $sfile for writing, reason $!\n";
	open(OUI, '>', $ifile) or die "Cannot open file $ifile for writing, reason $!\n";


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

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

	    if ( $chr eq $ch ) {

		$len = $row[2];
		$ref = $row[3];
		if ( $len == 0 && length($ref) == 1 ) {
		    print(OUS "$line\n");
		} else {
		    print(OUI "$line\n");
		}
	    } # end of chr if loop                                  
	} # end of while loop                    

	close(OUS);
	close(OUI);
	close(IN);

    } # end of chr loop
} # end of mouse loop
