#!/usr/bin/perl

use warnings;                             # warn me about the sh.. I wrote
use strict;                               # catch errors as early as possible
use Getopt::Std;                          # helps you to parse the command line
use Data::Dumper;                         # for debugging
use File::Find ();                        # for finding files
use Cwd ();

my $outputFile = "catlist.h";
my $inputDir = shift( @ARGV );
my $catNames = "";
my @categories;
my $nvars;

# the command line option flags - imported from Getopt::Std module
our ($opt_h, $opt_v);

# get options from the command line
getopts( 'hv' );

if ($opt_h)
{
   &showHelp;
   exit( 0 );
}

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, $inputDir );

# Replace all = by whitespace
$catNames =~ s/=/ /g;

# Remove all "const Cat_t declaration in front of variable definition
$catNames =~ s/const Cat_t //g;

# Remove all "const Int_t declaration in front of variable definition
$catNames =~ s/const Int_t //g;

# Remove all ; from string
$catNames =~ s/;//g;

# Remove all whitespace around +
$catNames =~ s/ \+ /+/g;

# Remove all commets
$catNames =~ s#//.*\n#\n#gm;

@categories = split " ",$catNames;

$nvars = scalar @categories;

if ($outputFile)
{
    open( OUTPUTFILE, ">$outputFile" )
      or die "ERROR: Can not open output file: $outputFile\n";
    if($opt_v)
      {
	print "File opened";
      }
    printf( OUTPUTFILE "#define CATLISTSIZE $nvars\n");
    printf( OUTPUTFILE "struct catMap { const char name[40]; Int_t value;};\n");
    printf( OUTPUTFILE "catMap Categories[$nvars]={\n");

    for(my $i=0;$i<$nvars;$i++)
      {
	if($i == $nvars-2)
	  {
	    printf( OUTPUTFILE "{\"".$categories[$i]."\",".$categories[$i+1]."}\n");
	    printf( OUTPUTFILE "};\n");
	  }
	else
	  {
	    printf( OUTPUTFILE "{\"".$categories[$i]."\",".$categories[$i+1]."},\n");
	  }
	$i++;
      }
   close ( OUTPUTFILE );
}
exit ( 0 );

sub wanted {
    /^.*def\.h\z/s &&
    &doexec(0, 'grep','cat',$_);
}

my $cwd = Cwd::cwd();

sub doexec {
    my $ok = shift;
    if ($ok)
      {
	my $old = select(STDOUT);
        $| = 1;
        print "@_";
        select($old);
        return 0 unless <STDIN> =~ /^y/;
      }
    $cwd = Cwd::cwd();
    chdir $cwd; #sigh
    $catNames = $catNames . ` @_`;
    chdir $File::Find::dir;
    return !$?;
}

sub showHelp
{
   print <<"EOF";

    makeCatlist - creat a headerfile with a structure containing category names ant there corresponding interer id\'s.
		  Used to do mapping with the asciiIntMap class.

EOF
}
