#! /usr/bin/perl -w

use strict;
use Bio::SeqIO;
use Data::Dumper;

my $shortened_id = 1;
my $reference_seq = "";

my @files;
foreach my $argnum (0 .. $#ARGV) {
	push @files, $ARGV[$argnum];
}

my %sequences;
my %seq_counts;
my $total_length = 0;;

foreach my $file(@files) {
	my $stream = Bio::SeqIO->new(-file => $file,
			      -format => 'Fasta');
	my $length;
	while ( my $seq = $stream->next_seq() ) {
		$length = length($seq->seq());
		my $seq_id = $seq->display_id();
		$seq_id = $1 if($shortened_id && $seq_id =~ /(\w+)_.*/);
		if($sequences{$seq_id}){
			$sequences{$seq_id} = $sequences{$seq_id} . $seq->seq();
		} else {
			$sequences{$seq_id} = ('-' x $total_length ) . $seq->seq();
		}
    }
	$total_length += $length;

	foreach my $key(keys(%sequences)) {
		if(length($sequences{$key}) < $total_length){
			$sequences{$key} = $sequences{$key} . ('-'x$length);
		}
	}
}

if($reference_seq){
	my @gap_positions;
	my $seq = $sequences{$reference_seq};
	my $gap_pos = index $seq,"-",0;
	
	foreach my $key(keys(%sequences)) {
		next if($key eq $reference_seq);
		my @arr = split('',$sequences{$key});
		my $count = 0;
		for(my $i=0;$i<@arr;$i++){
			if($arr[$i] eq '-'){
				$arr[$i] = -2;
			} else {
				$arr[$i] = $count++;
			}
		}
		$seq_counts{$key} = \@arr;
	}
	
	while($gap_pos != -1){
		open( AAA, ">>tmp");
		substr($seq, $gap_pos, 1, "o");
		
		foreach my $key(keys(%sequences)) {
			next if($key eq $reference_seq);
			substr($sequences{$key}, $gap_pos, 1, 'o');
			my @arr =  @{$seq_counts{$key}};
			$arr[$gap_pos] = -3;
			$seq_counts{$key} = \@arr;
		}
		$gap_pos = index $seq,'-';
		print AAA "\n$gap_pos";
		close AAA;
	}

	$sequences{$reference_seq} = $seq;	

	foreach my $key(keys(%sequences)) {
		open( AAA, ">>tmp");
		print AAA "\n$key";
		close AAA;
		next if($key eq $reference_seq);
		my @arr =  @{$seq_counts{$key}};
		my @frame_pos;
		my $frame = 0;
		#print Dumper(\@arr);
		#print "$key\n";
		for(my $i=0;$i<@arr;$i++){
			#print Dumper(\@arr);
			#print "$i\n";
			#print "$arr[$i]\n";	
			next if($arr[$i] == -3);
			$frame_pos[$frame] = $i;
			$frame = ($frame + 1) % 3;
			if($frame == 0){
				#print "$frame_pos[0]\n$frame_pos[1]\n$frame_pos[2]";
				if($arr[$frame_pos[0]] % 3 != 0 || 
					$arr[$frame_pos[0]] + 1 != $arr[$frame_pos[1]] ||
					$arr[$frame_pos[1]] + 1 != $arr[$frame_pos[2]]){
					substr($sequences{$key}, $frame_pos[0], 1, '-');
					substr($sequences{$key}, $frame_pos[1], 1, '-');
					substr($sequences{$key}, $frame_pos[2], 1, '-');
				}
			}
		}
	}

	
}

foreach my $key(keys(%sequences)) {
	$sequences{$key} =~ s/o//g;
	print ">$key\n$sequences{$key}\n";
}