#
# $Id: constants.c.PL,v 29.1 2007/04/09 11:14:42 biersma Exp $
#
# (c) 1999-2007 Morgan Stanley Dean Witter and Co.
# See ..../src/LICENSE for terms of distribution.
#

use English;
use File::Basename;

require "../util/parse_config";
require "../util/parse_headers";

open(CONSTANTS,">constants.c.$$")
  or die "Unable to open constants.c.$$: $ERRNO\n";

select(CONSTANTS);

print <<"EndOfHeader";
/*
 * This file is auto-generated by constants.c.PL
 */

/*
 * Obscene Hack Alert!!!!
 *
 * We cant seem to get the right errno macros unless we define a bunch
 * of macros, and those are all done for us in perl.h.  However, if we
 * do this on other platforms (than SGI), were getting failures
 * compiling with 5.004, due to the symbol table being too large.
 */
#if defined(__sgi)
#include "EXTERN.h"
#include "perl.h"
#endif

#include <errno.h>
#include <string.h>

/*
 * Constants were found from the following header files:
 */

EndOfHeader

#
# cmqc.h must be included first, otherwise, cmqbc.h will explode.
#
foreach my $header ( grep(/cmqc\.h$/,@headers),
		     grep(!/cmqc\.h$/,@headers) ) {
    my $filename = basename($header);
    print "#include <$filename>\n";
}
	
print "\n\n";

#
# Generate the constant_hex function
#
print <<"EndOfText";
MQULONG
constant_hex(name)
char *name;
{
    errno = 0;

EndOfText

foreach $constant ( sort keys %constant_hex ) {
    print <<"EndOfText";
    if ( strcmp(name, "$constant") == 0 )
       return $constant;

EndOfText
}

print <<"EndOfText";
    errno = ENOENT;

    return 0;
}

EndOfText

#
# Generate the constant_numeric function
#
print <<"EndOfText";
MQLONG
constant_numeric(name)
char *name;
{
    errno = 0;

EndOfText

foreach $constant ( sort keys %constant_numeric ) {
    print <<"EndOfText";
    if ( strcmp(name, "$constant") == 0 )
       return $constant;

EndOfText
}

print <<"EndOfText";
    errno = ENOENT;
    return 0;
}

EndOfText

#
# Now generate the constant_string function
#
print <<"EndOfText";
int
constant_string(name,value)
char * name;
char * value;
{
    errno = 0;

EndOfText

foreach $constant ( sort keys %constant_string ) {

    print <<"EndOfText";

    if ( strcmp(name, "$constant") == 0 ) {
	strcpy(value,$constant);
	return 1;
    }

EndOfText
}

print <<"EndOfText";

    errno = ENOENT;
    return 0;

}
EndOfText

#
# Now generate the constant_char function
#
print <<"EndOfText";
int
constant_char(name,value)
char * name;
char * value;
{
    errno = 0;

EndOfText

foreach $constant ( sort keys %constant_char ) {

    print <<"EndOfText";

    if ( strcmp(name, "$constant") == 0 ) {
	value[0] = $constant;
	return 1;
    }

EndOfText
}

print <<"EndOfText";

    errno = ENOENT;
    return 0;

}
EndOfText

close(CONSTANTS) ||
  die "Unable to close constants.c.$$: $ERRNO\n";

rename("constants.c.$$","constants.c") ||
  die "Unable to rename constants.c.$$ to constants.c: $ERRNO\n";

exit 0;

