#!/usr/bin/perl -w

#
# This script scans the headers of a FASTA file provided at STDIN,
# numbers each record starting from one, replacing original headers
# and writes out a file_for_RE.tab file with a table mapping original
# headers to the new ones. The renumbered FASTA file is written out
# at STDOUT. The input FASTA file must be exactly 2 lines per record,
# no other lines will be tolerated. If there are arguments to the
# script, the first one is used as table file name base.
#
# Matej Lexa 2021
#

$num = 1; # used for numbering reads starting from 1
@map = (); # used to prepare the mapping table
if($ARGV[0] ne "") {
  $table_base = $ARGV[0];
} else {
  $table_base = "file_for_RE";
}

# process STDIN to STDOUT
while($_=<STDIN>) {
  $_ =~ s/^>([^ \t]+)[ \t]+.+$/>$num/;
  $old_header = $1;
  push(@map,"$old_header\t$num"); # build map table
  print $_; # print modified header
  $_=<STDIN>;
  print $_; # print sequence line
  $num++;
}

# output mapping table
open(TABLE,">$table_base.tab");
foreach(@map) {
  print TABLE "$_\n";
}
close(TABLE);

exit 1;

