#!/usr/bin/perl -w

use strict;
use POSIX;
use Eseries;
use Opt qw/ %OPT /;
use Prefix;

sub main() {
    @ARGV = Opt::opt();

    Eseries::show();

    if (
	(!defined($OPT{num}) || !defined($OPT{digits})) &&
	(!defined($OPT{min}) || !defined($OPT{max}   )) &&
	!defined($OPT{E}) && @ARGV < 1
    ) {
	print
"Usage: $0 num=.. digits=.. min=.. max=.. E=... values...
";
	return;
    }

    Prefix::decode_hash(\%OPT);
    my @Egen;
    my @Earg;
    my @Estd;
    my @Eopt;

    print "########\n\n";
    if ( defined($OPT{num}) && defined($OPT{digits}) ) {
	print "num = $OPT{num}\n";
	print "digits = $OPT{digits}\n";
	@Egen = Eseries::Eseries($OPT{num},$OPT{digits});
	Eseries::print_arr(12, '@Egen', @Egen);


	my $digits = Eseries::type(@Egen);
	print "type(\@Egen) = $digits\n\n";

	if ( defined($OPT{min}) && defined($OPT{max}) ) {
	    @Egen = Eseries::ExpandLimit($OPT{min},$OPT{max}, @Egen);
	    Eseries::print_arr(12, "[Egen]", @Egen );
	}

	print "########\n\n";
    }

    if (@ARGV) {
	@Earg = Eseries::sort_numbers(@ARGV);
	Eseries::print_arr(12, '@E', @Earg);
	my $digits = Eseries::type(@Earg) // "undef";
	print "type(\@Earg) = $digits\n";
	print "########\n\n";
    }

    if ( defined($OPT{min}) && defined($OPT{max}) ) {
	print "min = $OPT{min}\n";
	print "max = $OPT{max}\n";

	my @Estd = Eseries::ExpandLimit($OPT{min},$OPT{max}, @Eseries::E192);
	Eseries::print_arr(12, "[E192]", @Estd );
	print "########\n\n";
    }

    if ( defined($OPT{E}) ) {
	@Eopt = Eseries::find($OPT{E});
	Eseries::print_arr(12, $OPT{E}, @Eopt);
	if ( defined($OPT{min}) && defined($OPT{max}) ) {
	    @Eopt = Eseries::ExpandLimit($OPT{min},$OPT{max}, @Eopt);
	    Eseries::print_arr(12, $OPT{E}, @Eopt);
	}
	print "########\n\n";
    }

    if (defined($OPT{val})) {
	my @val;
	my @E = @Eopt;
	if (@E == 0) { @E = @Earg; }
	if (@E == 0) { @E = @Egen; }
	if (@E == 0) { @E = @Estd; }
	@val = Eseries::nearest($OPT{val}, @E);
	print "nearest: ", join( " ", @val), "\n";
	print "########\n\n";
    }
}

main();
