#!/local/bin/perl

#
#	Copyright 1993, Center for Computer Vision and Visualization,
#	University of Florida.  All rights reserved.
#

#
# $Log: c-gen-nbh.perl,v $
# Revision 1.3  1994/08/22  15:20:29  thoth
# DOS-inspired name rework.
#
# Revision 1.2  1994/05/08  19:42:21  thoth
# Automatic neighborhood reductions require change in spec file.
#
# Revision 1.1  1994/01/31  16:50:30  thoth
# Initial revision
#

sub absorber_subst {
	local ($fname,
		$init, $forw_init, $accum, $accvar, $forw_accvar, $final,
		$rtype, $name, $itype, $zero) = @_;
	local ($ival, $tval, $rval) = ("#undef#","#undef#","#undef#");
	local($_);
	local($/) = -1;

	open(FILE, "<$fname") ||
		die "couldn't open $fname";

	$_ = <FILE>;

	if (m-^// _IVAL_=-) {
		print STDERR "IVAL: ", $';
	}

	s/\bFORW_INITIALIZE\b/$forw_init/g;
	s/\bINITIALIZE\b/$init/g;

	s/\bFORW_ACCUMULATEVAR\b/$forw_accvar/g;
	s/\bACCUMULATE\b/$accum/g;
	s/\bACCUMULATEVAR\b/$accvar/g;
	s/\bRESULT\b/$final/g;

	s/\bRTYPE\b/$rtype/g;
	s/CONV/$name/g;
	s/IBTYPE\b/$itype/g;
	s/\bZERO\b/$zero/g;

	local(@_) = split("\n");
	foreach (@_) {
		if (m:^\s*//\s*_IVAL_=:)    { $ival = $'; next; }
		if (m:^\s*//\s*_IRESULT_=:) { $rval = $'; next; }
		s/\bIVAL\b/$ival/g;
		s/\bIRESULT\b/$rval/g;
	}

	print join("\n", @_);
	print "\n";

	$/ = '\n';

	close(FILE);
}

while (<>) {
    next if /^\s*$/;

    if (/^#/) {
	print "//", $';
	next;
    } elsif (/^"H?C/) {
	print $';
	next;
    }

    print "// $_";

    @_ = split;

    local($sort) = shift(@_);

    if ($sort eq "neighborhood") {

	local($rtype, $name, $itype, @blah) = @_;

	@_ = @blah;

	local($zero);

	while (@_) {
	    $_ = shift(@_);

	    if (/^zero=/) {
		$zero = $';
	    } else {
		warn "Unknown option $_. ";
	    }
	}

	local($init,$accum,$accvar,$final,$forw_init,$forw_accumvar);

	while ($_ = <>) {
	    chop;
	    next if /^#/;
	    last if $_ eq "end";

	    if (0) {
#	    } elsif (/^init:\s*/) {
#		$init = $';
	    } elsif (/^accum:\s*/) {
		$accum = $';
	    } elsif (/^accvar:\s*/) {
		$accvar = $';
#	    } elsif (/^final:\s*/) {
#		$final = $';
	    } elsif (/^forw_init:\s*/) {
		$forw_init = $'
	    } elsif (/^forw_accumvar:\s*/) {
		$forw_accumvar = $'
	    } else {
		die "unknown nbh-reduction field: $_\n";
	    }
	}
#	defined $init || die "no initiazlier for backward reduction $name\n";
	defined $accum || die "no accumulator for backward reduction $name\n";
	$accvar = $accum unless defined $accvar;
#	defined $final || die "no final for backward reduction $name\n";
	defined $forw_init || die "no initializer for forward reduction $name\n";
	defined $forw_accumvar || die "no accumulator for forward reduction $name\n";

	if ($zero ne "") {
	    &absorber_subst("nbh-reduction", $init, $forw_init,
			    $accum, $accvar, $forw_accumvar, $final,
			    $rtype, $name, $itype, $zero);
	} else {
	    print "// non-absorbers not handled yet\n";
	}

	print "\n";
    }
}
