#!/usr/bin/perl -w

# Read/Write config (text) files

# use Cowgen::Config;

# $conf = Cowgen::Config::loadConfig("config.cfg");
# print "keyword => ",$conf->{keyword},"\n";
# Cowgen::Config::saveConfig($conf);

# (c) Copyright by Tels 1999-2000. All Rights Reserved. Do NOT distribute.
# Updates and support on bloodgate.com/thief

# 2000-01-18 v0.0.1 - first version
# 2000-04-23 v0.0.2 - fixed lc bug

package Cowgen::Config;
require Exporter;
@ISA    = qw(Exporter);
@EXPORT = qw( );
@EXPORT_OK = qw( loadConfig saveConfig );

use strict 'vars';

sub loadConfig
  {
  # read a config file and return hash containing all the keys/values. in 
  # config_filename is the file config was read from stored. On error an empty
  # hash is returned. (e.g. config_filename is empty)
  # parameter: filename
  my ($file) = @_;
  my $cfg = {}; my ($val,$var,$l,$comments);
  open FILE, $file or return $cfg;
  $cfg->{config_comments} = {}; $comments = [];
  while (<FILE>)
    {
    $l = $_;
    if (($l =~ /^#/) || ($l =~ /^\s*$/))
      {
      push (@$comments, $l); next; 
      }
    $l =~ s/\|//g;      # remove pipes (special char)
    $l =~ s/("[^"]*")/ nospace($1); /eg;
    $l =~ s/\s+//g; 
    $l =~ /^(.*?)=\"?(.*?)\"?$/;
    $var = lc($1); $val = $2; $val =~ s/\|/ /g;
    $val = 1 if ((lc($val) eq "on") || (lc($val) eq "true"));
    $val = 0 if ((lc($val) eq "off") || (lc($val) eq "false"));
    $cfg->{$var} = $val;
    $cfg->{config_comments}->{$var} = $comments; $comments = [];
    }
  close FILE; $cfg->{config_filename} = $file; 
  $cfg; # config
  }

sub saveConfig
  {
  # write a config to a file. 
  # parameter: confighash, filename (otpional)
  my $cfg = shift || return;
  my $file = shift || $cfg->{config_filename} || "config.cfg";
  open FILE, ">$file" or return $cfg;
  my ($t,$c);
  foreach (keys %$cfg)
    {
    next if /^config_(filename|comments)/;
    if (defined $cfg->{config_comments}->{$_})
      {
      foreach $c (@{$cfg->{config_comments}->{$_}})
        {
        print FILE $c;
        }
      }
    $t = $cfg->{$_};
    $t = "\"$t\"" if ($t =~ /\s/);
    print FILE "$_ => $t\n"; 
    }
  $cfg; # config
  }

sub nospace { my $t = shift; $t =~ s/\s/\|/g; $t; }

1;

