#! /usr/bin/perl -w 
#
# Written by Lucas Brutschy <lbrutschy@users.sourceforge.net>, 2006.
# 
use strict;

if($#ARGV!=2) { print "usage: updateproto.pl <modulefile> <enumfile> <protfile>\n"; }
else
{
    my ($file,$enumfile,$protofile) = @ARGV;
    rename $file, $file.".bak" or die $!;

    open(NEW,"> $file") or die $!;

    open(PM,"< $file.bak") or die $!;

    while(<PM>) {
	print NEW;
	if(/=head1 DESCRIPTION/) {
	    print NEW "\n=head2 Functions\n\n";
	    open(PROTO,"< $protofile") or die $!;
	    while(<PROTO>) {
		my (@command) = split /[\t\n]/;
		print NEW " $command[0]: $command[1]\n";
	    }
	    close(PROTO);

	    print NEW "\n=head2 Constants\n\n";
	    open(ENUM,"< $enumfile") or die $!;
	    while(<ENUM>) {
		my ($name,$value) = split /[\t\n]/;
		print NEW " $name\n";
	    }
	    close(ENUM);
	    print NEW "\n";
	    while(<PM>) {
		if (/^=head1 SEE ALSO/) { print NEW; last ; }
	    }
	}
	if(/# == prototypes == /) { last; }
    }
    close(PM);

    open(ENUM,"< $enumfile") or die $!;
    while(<ENUM>) {
        my ($name,$value) = split /[\t\n]/;
        print NEW "use constant $name => $value;\n";
    }
    close(ENUM);

    open(PROTO,"< $protofile") or die $!;
    while(<PROTO>) {
        my ($command) = split /[\t\n]/;
        print NEW "sub $command { return send_command('$command',\@_); }\n";
    }
    close(PROTO);

    print NEW "1;\n";

    close(NEW);
}
