#!/usr/bin/perl

@fileList = @ARGV;

$orgFile = @fileList[0];

print STDERR "Reading original FASTA file...\n";
open (ORG, $orgFile);
while (chomp($line = <ORG>)) {
  if (substr($line, 0, 1) eq ">") {
    ($id) = split(' ', $line);
    $id =~ s/>//;
    $mapping{$id} = $line;
  }
}
close ORG;

for ($f = 1; $f < scalar(@fileList); $f++) {
  $filename = @fileList[$f];
  print STDERR "Processing file $f ($filename)...\n";
  $newfile = "$filename.restored.fasta"; 
  open (ITS, $filename);
  open (OUTPUT, ">$newfile");
  while (chomp($line = <ITS>)) {
    if (substr($line, 0, 1) eq ">") {
      ($id) = split(' ', $line);
      $id =~ s/>//;
      $procid = substr($id, 0, -7);
      if (exists($mapping{$procid})) {
	$header = $mapping{$procid};
      } else {
	$header = $line;
      }
      print OUTPUT $header . "\n";
    } else {
      print OUTPUT $line . "\n";
    }
  }
  close ITS;
  close OUTPUT;
}
print STDERR "Finished!\n";

