#!/usr/bin/perl -w

# USAGE: x002dat.pl *.x00
# (C) Jochen Puchalla 2005

$good=0;
$bad=0;

foreach $file (@ARGV) 
{
	if (! open(INPUT,"<$file") ) 
	{
		print STDERR "Can't open input file $file\n";
		$bad++;
		next;
	}
	
	$filecore=$file;
	$filecore =~ s/.x00$//g;
	
	if ($file eq $filecore)  
	{
		print STDERR "$file is not an x00 file\n";
		$bad++;
		next;
	}

	# open output file:	
	if (! open(OUTPUT,">$filecore.dat") ) { print STDERR "Can't open output file $filecore.dat\n"; $bad++; next; }
	
	print "Generating $filecore.dat\n";
	$good++;

while ($line=<INPUT>) 
	{
		$line =~ s/[\n\r]$//g; #remove newline at end of string
		
		if ($line =~ /^FirstAngle/)
		{
			@values = split(/\s/, $line);
			$pos = $values[1];
		}
		
		if ($line =~ /^StepWidth/)
		{
			@values = split(/\s/, $line);
			$step = $values[1];
		}
		
		if ($line =~ /^\d/)
		{
			printf OUTPUT "%.3f %.4f\n",$pos,$line;
			$pos = $pos + $step;
		}
	}
	
	close INPUT;
	open(INPUT,"<$file");
	
	# handle header:
	while ( ($line=<INPUT>) =~ /^[A-Z]/i ) { print OUTPUT "# $line"; } #if line starts with letter, copy it
	
	close INPUT;
	close OUTPUT;
}

if ($good==0) {print "\nDid not generate a file\n";}
if ($good==1) {print "\nGenerated one file\n";} 
if ($good>1) {print "\nGenerated $good files\n";}
if ($bad==0) {print "There was no problematic file\n";}
if ($bad==1) {print "There was one problematic file\n";}
if ($bad>1) {print "There were $bad problematic files\n";}

exit(0); 
