$file1=shift;
$file2=shift;

use Data::Dumper;

open(A,"$file1");
$line=1;
while(<A>)
{
	$linha=$_;
	if ($linha=~/(\{\d+\}\{\d+})/)
	{
		$frames=$1;
	}
	while($_=~/([A-Z][a-z]+)(.*)/)
		{
			$_=$2;
			push @{$fich1{$1}},$frames;
		}
		$line++;
	
}

open(A,"$file2");

while(<A>)
{
	$linha=$_;
	if ($linha=~/(\{\d+\}\{\d+})/)
	{
		$frames=$1;
				
	}
	while($_=~/([A-Z][a-z]+)(.*)/)
		{
			$_=$2;
			push @{$fich2{$1}},$frames;
		}

	
}

$alinh=0;
for (keys %fich1)
{
	if(defined $fich2{$_})
	{
		@a=@{$fich1{$_}};
		@b=@{$fich2{$_}};
		$n1=0;
		
		$na=0;
		for $pal(@a)
		{
			$n1++;
			$n2=0;
			for $pal2(@b)
			{
				$n2++;
				if($pal=~/^\{(\d+)\}/)
				{
					$fr1=$1;
					if($pal2=~/^\{(\d+)\}/)
					{
						if(($fr1+25>$1) && ($fr1-25<$1))
						{
							$na++;
							$key="$pal $pal2"; 
							$aligned{$fr1}=$key;
							$alinh++;
							
						}
					}
				}
				
			}
			
		}
			

	}
}


for (sort {$a <=> $b} keys %aligned)
{
	@frames=split(/ /,$aligned{$_});

	push @text1,$frames[0];
	push @text2,$frames[1];
}

open(A,$file1);
open(B,$file2);
@t1=<A>;
@t2=<B>;


$tam=@text1;
$v=0;
$count=0;
$text1[0]=~s/\{/\\\{/g;
$text1[0]=~s/\}/\\\}/g;
for (@t1)
{

	if (($_=~/$text1[0]/gi) && ($text1[0] ne ""))
	{
	

		push @temp1,$count;
		$count=0;
		shift @text1;
		$text1[0]=~s/\{/\\\{/g;
		$text1[0]=~s/\}/\\\}/g;
	}
	else {
		$count++;
	}

}
push @temp1,$count;
$count=0;
$text2[0]=~s/\{/\\\{/g;
$text2[0]=~s/\}/\\\}/g;
for (@t2)
{	
	
	if (($_=~/$text2[0]/) && ($text2[0] ne ""))
	{
	
		push @temp2,$count;
		$count=0;
		shift @text2;
		$text2[0]=~s/\{/\\\{/g;
		$text2[0]=~s/\}/\\\}/g;
	}
	else {
		$count++;
	}
	
}
push @temp2,$count;


$tam1=@temp1;
$tam2=@temp2;
open(D,">$file1.aligned");
open(E,">$file2.aligned");

$linecount1=1;
$linecount2=1;
for ($i=0;$i<$tam1;$i++)
{
	if ($temp1[$i]==$temp2[$i])
	{
		for ($j=0;$j<=$temp1[$i];$j++)
		{
			$l=shift(@t1);
			print D "$l";
			print D "\$\n";
			$linecount1++;
		}

		for ($j=0;$j<=$temp2[$i];$j++)
		{
			$l=shift(@t2);
			print E "$l";
			print E "\$\n";
			$linecount2++;
		}

		
	}
	else 
	{
		

		
		
		for ($j=0;$j<$temp1[$i];$j++)
		{
			$l=shift(@t1);
			print D $l;
		
		}

		for ($j=0;$j<$temp2[$i];$j++)
		{
			$l=shift(@t2);
			print E $l;
		
		}

		print D "\$\n";
		print E "\$\n";
		$linecount1++;
		$linecount2++;
	}
	

}
