#!/usr/bin/perl

use strict;

use lib 'd:/Programs/Perl/lib';

use Utils;
use JFile;

my $Source1 = 'XPS-BE-Source.csv';
#my $Source2 = 'XPS-BE-Small.csv';

my $SearchVal = ''; #510; # eV
my $SearchErr = ''; #  5; # eV
if($SearchVal eq '') {
	print "Input search value (Def: 510 eV): ";
	my $line = <>;
	Utils::DelSpace($line);
	if($line eq '') {
		$SearchVal = 510.0;
	}
	else {
		$SearchVal = $line + 0.0;
	}
}
print "Input error value (Def: 10 eV): ";
if($SearchErr eq '') {
	my $line = <>;
	Utils::DelSpace($line);
	if($line eq '') {
		$SearchErr = 10.0;
	}
	else {
		$SearchErr = $line + 0.0;
	}
}

print "Read [$Source1] =====================================\n";
my $pBE1 = &ReadCSV($Source1);
#print "Read [$Source2] =====================================\n";
#my $pBE2 = &ReadCSV($Source2);

print "=====================================\n";
&Search($pBE1, $SearchVal, $SearchErr);

exit;

sub Search
{
	my ($p, $t, $e) = @_;

print "Hit for ", $t - $e , " - ", $t, " - ", $t + $e, " eV ...\n";
	foreach my $key (sort keys %$p) {
		my $v = $p->{$key};
#print "comp: $v ($t +- $e ?)\n";
		if($t - $e <= $v and $v <= $t + $e) {
			my ($an, $name, $st) = split(/\s+/, $key);
			printf("  %2d %2s %8s   %8.2f eV\n", $an, $name, $st, $v);
		}
	}
}

sub ReadCSV
{
	my ($infile) = @_;

	my $in = new JFile;
	if(!$in->Open($infile, 'r')) {
		print "Error: Can not read [$infile]\n\n";
		exit;
	}

	my %hash;
	my $header;
	my @st;
	my @val;
	while(1) {
		my $line = $in->ReadLine();
		last if(!defined $line);

#print "l: $line";
		if($line =~ /s/i and $line =~ /p/i and $line =~ /d/i) {
			@st = split(/\s*,\s*/, $line);
print "st=", join(', ', @st), "\n";
		}
		else {
			@val = split(/\s*,\s*/, $line);
#print "  v=", join(', ', @val), "\n";
			for(my $i = 2 ; $i < @val ; $i++) {
				my $o = $st[$i];
				my $key = "$val[0] $val[1] $o";
				$hash{$key} = $val[$i] + 0.0;
print "  $key: $hash{$key}\n";
			}
		}
	}
	
	$in->Close();
	
	return \%hash;
}