#!perl

#
# Generate the string functions from "str_fct.dat" data file
# Also generate DOC\SSTR.FCT, a LaTeX source
#
#	All functions do accept NULL for a pointer and either tread
#	this string as "" or does not perform any action.
#

# Known function groups: old->new
%fmap = (
	'str', 'Str',
	'stp', 'Stp',
	'mem', 'Mem'	);

die "Cannot open sstr.src" unless open(IN, "sstr.src");
die "Cannot create str_func.mk" unless open(STR, ">str_func.mk");
die "Cannot create sstr.h" unless open(HDR, ">sstr.h");
die "Cannot create doc\\sstr.fct"  unless open(TEX, ">doc\\sstr.fct");
print HDR "/* This file was automatically generated from SSTR.SRC */\n";
print HDR while <IN>;		# Copy the standard header file
close IN;
print TEX "%%\n%% This file was automatically generated by MKSTRFCT.PL\n%%\n";
print HDR "\n\n/* Generated string function replacements */\n";

# @ARGV = ('str_fct.dat');

$cnt = 0;

print STR "STRFCT_SRC = ";		# Prepare Makefile


while(<>) {
	next if /^\s*$/ || /^\s*\#/;
	if($cnt && /^\t/) {	# Body of function
		s/\@/$fctcall/g;
		print OUT;
	} elsif(/([a-zA-Z_0-9]+)(\([^\)]+\))/) {	# new function
		$name = $1;
		$returnType = $`;
		$argList = $2;

		if($cnt) {
			print OUT "}\n";
			close OUT;
		}

		$type = substr($name, 0, 3);
		die "Unknown function type $name" unless defined $fmap{$type};
		$lname = $fmap{$type} . substr($name, 3);

		print TEX "\\fct{$lname()},\n";

		@args = split(',', substr($argList, 1, length($argList) - 2));
		foreach $i (0..$#args) {
			$args[$i] = $1 if $args[$i] =~ /([A-Za-z0-9_]+)[^A-Za-z0-9_]*$/;
		}
		$fctcall = $name . '(' . join(', ', @args) . ')';

		$fnam = &nxtFnam;
		print STR "\\\n\t$fnam ";		# dump the current filename

		die "Cannot create file $fnam" unless open(OUT, ">$fnam");
		print OUT "/* DON'T MODIFY THIS FILE!

	This is an auto-generated file (by mkstrfct.pl), don't
	modify because next time the script runs, your modifications
	are lost.

	Defines one of the string functions replacements that accept
	NULL as pointer arguments.
*/

#include \"initsupl.loc\"

#ifndef _MICROC_ 
#include <string.h>
#endif
#include <portable.h>
#include \"suppl.h\"
#ifdef SUPPL_STR_REMAP
#undef SUPPL_STR_REMAP
#endif
#include \"sstr.h\"

$returnType$lname$argList
{
";
		print HDR "$returnType$lname$argList;\n";
		$nmap{$name} = $lname;
	} else {
		die "Syntax error";
	}
}

print OUT "}\n";
close OUT;

DEL: {
	$fnam = &nxtFnam;
	if(-e $fnam) {
		unlink $fnam;
		redo DEL;
	}
}

sub nxtFnam {
	return sprintf("stfc_%03x.c", ++$cnt);
}

print STR "\n";

print HDR "\n\n#ifdef SUPPL_STR_REMAP\n\t/*Remap standard function names to replacements */\n\n";
while( ($name, $lname) = each %nmap) {
	print HDR "#define $name $lname\n";
}
print HDR "#endif	/* defined(SUPPL_STR_REMAP) */\n\n#endif\n";

close STR;
close HDR;
