#!/usr/bin/perl
#
#   Copyright (C) 2007 Mark Wedel & Crossfire Development Team
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   The author can be reached via e-mail to crossfire-devel@real-time.com
#

# $ARGV[0] is the source directory. We need to know it for out of tree builds.
open(IN,"<$ARGV[0]/shared/newclient.h") || die("Can not open newclient.h file\n");
open(OUT,">$ARGV[0]/msgtypes.h") || die("Can not open msgtypes.h file\n");

print OUT "/* This file is automatically generated. Editing by hand is strongly */\n";
print OUT "/* discouraged.  Look at the newclient.h file and the msgtypes.pl conversion */\n";
print OUT "/* script. */\n";

print OUT "\nconst Msg_Type_Names msg_type_names[] = {\n";
print OUT "{0, 0, \"generic\"},\n";

$on_subtypes=0;
$last_type=0;

while(<IN>) {
    if (/^#define\s+MSG_TYPE_(\S*)/) {
	if ($1 eq "LAST" || $1 eq "SUBTYPE_NONE") {
	    $on_subtypes=1;
	    next;
	}
	$type = $1;
	$lc = $1;
	$lc =~ tr /A-Z/a-z/;
	if (! $on_subtypes) {
	    $types[$max_types++] = $1;
	    print OUT "{MSG_TYPE_$1, 0, \"$lc\"},\n";
	} else {
	    if ($type !~ /^$types[$last_type]/ ) {
		for ($i=0; $i< $max_types; $i++) {
		    if ($type =~ /^$types[$i]/) {
			$last_type=$i;
			last;
		    }
		}
		if ($i == $max_types) {
		    print STDERR "Unable to find right type for $type\n";
		}
	    }
	    print OUT "{MSG_TYPE_$types[$last_type], MSG_TYPE_$type, \"$lc\"},\n";
	}
    }
}
close(IN);

print OUT "};\n";
close(OUT);
