package ReportGen::ObjDbase;
use strict;

# manipulates object database that is stored using the following
# text format
#
#              <name>: <body>\n
# or
#              <name>:\n
#              <multiline-body>
#              \n


require Exporter;

@ReportGen::ObjDbase::ISA = qw ( Exporter );
@ReportGen::ObjDbase::EXPORT = qw ( &ReadDbase );

#
# returns a hash representing the objects read
#
sub ReadDbase {
	my ($fname, $mayFail) = @_;

	my $dbase = {};
	if (!open(IF, "<$fname")) {
		die("$0: cannot open `$fname': $!\n") unless $mayFail;
		return undef();
	}

	my $lineno = 0;
	while (<IF>) {
		$lineno++;
		next if /^\#/;
		next if /^\s*$/;
		$_ =~ s/\s*(?<!\\)\#.*$//g;

		my $loc = "$fname:$lineno";
		#warn("$loc: $_");
		if (/^([^:]+?):\s*(\S+.*)$/) {
			next if $2 eq '?';
			$dbase->{"$1"} = {
				name => $1,
				body => $2,
				atom => 1,
				loc  => $loc,
			};
		}
		elsif (/^([^:]+?):$/) {
			my $multiline;
			$dbase->{"$1"} = $multiline = {
				name  => $1,
				lines => [],
				atom  => 0,
				loc  => $loc,
			};
			while (<IF>) {
				$lineno++;
				last if /^\s*$/;
				push @{$multiline->{lines}}, $_;
			}
			$multiline->{body} = join('', @{$multiline->{lines}});
		} elsif (/^([^:]+?){$/) {
			my $multiline;
			$dbase->{"$1"} = $multiline = {
				name  => $1,
				body => '',
				atom => 0,
				verb  => 1,
				loc  => $loc,
			};
			while (<IF>) {
				$lineno++;
				last if /^}\s*$/;
				$multiline->{body} .= $_;
			}
		} else {
			die("$loc: unrecognized entry near `$_'\n");
		}
	}

	close(IF);

	return $dbase;
}


syntax highlighted by Code2HTML, v. 0.9.1