package Constants;

#semi-constructor

sub load() {
    %terms = ();
    my $filename = shift;
    open FD, $filename;
    my $count = 0;
    while ($line = <FD>) {
        chomp $line;
        next unless $line and $line !~ /^#/;
        my ($key, $value) = Constants::split_terms($line, ++$count);
        $key = "\U$key\E";
        if ('ERROR' eq $key) {
            print STDERR "Error in $value\n";
            next;
        }
        $terms{$key} = $value;
        #print "$key -> $value\n";
    }
    close FD;
    return %terms;
}

sub split_terms {
    my $line = shift;
    my $count = shift;
    my $label = shift or "Line";
    my ($key, $value) = split(/\s*=|:\s*/, $line, 2);
    if (! $value) {
        ($key, $value) = ('error', sprintf("$label %d: No key-value pair in '%s'", $count, $key));
    }
    my @too_far = split(m=\s|-|%|\$|\@|,|/=, $key);
    if (@too_far > 1) {
        ($key, $value) = ('error', sprintf("$label %d: key must not contain whitespace or '-%$@,/", $count, $key));
    }
    $key = strip($key);
    $value = strip($value);
    return ($key, $value)
}

sub strip() {
    my $term = shift;
    $term =~ s/^\s*\b(\w.*\w)\b\s*$/$1/;
    return $term;
}
1;
