#!/usr/bin/perl -w

use strict;
use File::Copy;

my $usage = <<USAGE
The script will collect the MassSpectrum.xml files found in a project and copy them to the top level directory with new names, based on the raw file names.
Usage: perl RenamePLGSfiles.pl <PLGS project directory>

Example: perl RenamePLGSfiles.pl x:/Username/Proj__11739475298910_9281147836835626
USAGE
  ;

die $usage unless scalar(@ARGV) == 1;

my @dirs = glob("$ARGV[0]/\*");

my $counter = 0;
foreach my $dir ( @dirs ) 
{
    next unless -d $dir;         # Skip non-directories
	my $file="$dir/MassSpectrum.xml";
 	if (open(FIN, '<', "$dir/MassSpectrum.xml"))
	{
		my $shortname;
       		while (my $line = <FIN> )
		{
		if ($line =~ /^<MASS_SPECTRUM.*/)
			{
			my $i=rindex $line,"\\";
			my $j=index $line,".raw";
			$shortname=substr($line,$i+1,($j-$i-1));
			}
		}				
		close(FIN);
		my $outfile = "$ARGV[0]/$shortname.plgs";
		print "$outfile\n";
		copy($file, $outfile);
	}
}

