#!/usr/bin/perl -w

my @includes;

my %cmdnames;
my %cmdlevels;
my %cmdargs;
my %cmddesc;
my %protos;

my $infunc = 0;

while (<>) {
  chomp;
  
  if (/^#include (.*)$/) {
#    print "Adding include: $1\n";
    push @includes, $1;
    next;
  }
  
  if (/chanservaddcommand\((.*)\)/) {
#    print "Found \"addcommand\" stanza\n";
    my $args=$1;

    unless ($args =~ m!^\s*"([^"]+)"\s*,\s*([^,]+?)\s*,\s*(\d+)\s*,\s*([^, ]+)\s*,\s*"([^"]+)! ) {
      print "Can't decode addcommand() args: $args\n";
      next;
    }
#    print "Command function is: $4\n";
    
    $cmdnames{$4} = $1;
    $cmdlevels{$4} = $2;
    $cmdargs{$4} = $3;
    $cmddesc{$4} = $5;
  }

  if (/^int (.*?)\(.*;/) {
    print "Found prototype for function: $1\n";
    $protos{$1}=$_;
  }
  
  if (/^int (\S+)\s*\(.*{/) {
    print "Found start of function declaration: $1\n";
    unless (defined $cmdnames{$1}) {
      print "Found function $1 without definition, skipping ...\n";
      next;
    }
        
    my $fname = $cmdnames{$1}.".c";
    
    open CMDF, ">".$fname;
    
    print CMDF "/* Automatically generated by refactor.pl.\n *\n *\n";
    print CMDF " * CMDNAME: $cmdnames{$1}\n";
    print CMDF " * CMDLEVEL: $cmdlevels{$1}\n";
    print CMDF " * CMDARGS: $cmdargs{$1}\n";
    print CMDF " * CMDDESC: $cmddesc{$1}\n";
    print CMDF " * CMDFUNC: $1\n";
    print CMDF " * CMDPROTO: $protos{$1}\n";
    print CMDF " */\n\n";
    
    for (@includes) {
      print CMDF "#include $_\n";
    }
     
    print CMDF "\n";
    print CMDF "$_\n"; 
    
    $infunc=1;
    next;
  }
  
  if ($infunc) {
    print CMDF "$_\n";
    if (/^}/) {
      close CMDF;
      $infunc=0;
    }
  }
}
