# reads in configuration files

package cfgread;


sub read_cfg_line {
    my ($handle) = @_;
    my $line = "";

    while (defined($line = <$handle>)) {
	$line =~ s/^\#.*$//; # remove comments
	$line =~ s/\cM|\cJ//g; # remove end-of-line characters
	if ($line =~ /\w/) {
	    my @line = split(/\t/, $line);
	    return \@line;
	}
    }
    return undef;
}

sub write_cfg_line {
    my ($handle, $line) = @_;
    print $handle join ("\t", @$line), "\n";
}


# stringexp and arrayexp should be something like
#   '^(this|that)$'
sub read_cfg_file {
    my ($filename, $stringexp, $arrayexp) = @_;
    my ($line);
    my $data = {};

    if (open (COLCFG, $filename)) {
	while (defined ($line = &read_cfg_line('COLCFG'))) {
	    if (scalar(@$line) >= 2) {
		my $key = shift (@$line);
		if ($key =~ /$stringexp/) {
		    $data->{$key} = shift (@$line);

		} elsif ($key =~ /$arrayexp/) {
		    push (@{$data->{$key}}, @$line);
		}
	    }
	}
	close (COLCFG);
    } else {
	print STDERR "cfgread::read_cfg_file couldn't read the cfg file $filename\n";
    }

    return $data;
}


# stringexp and arrayexp should be something like
#   '^(this|that)$'
sub write_cfg_file {
    my ($filename, $data, $stringexp, $arrayexp) = @_;

    if (open (COLCFG, ">$filename")) {
	foreach $key (sort(keys(%$data))) {
	    if ($key =~ /$stringexp/) {
		&write_cfg_line ('COLCFG', [$key, $data->{$key}]);
	    } elsif ($key =~ /$arrayexp/) {
		&write_cfg_line ('COLCFG', [$key, @{$data->{$key}}]);
	    }
	}
	close (COLCFG);
    } else {
	print STDERR "cfgread::write_cfg_file couldn't write the cfg file $filename\n";
    }
}


1;
