#!/usr/bin/perl

require 'c_types.pl';

die "Usage: $0 features.def command.h.in" unless $#ARGV == 1;

$[ = 1;			# set array base to 1
$, = ' ';		# set output field separator
$\ = "\n";		# set output record separator

sub toupper {
    local($_) = @_;
    tr/a-z/A-Z/;
    return $_;
}

sub tolower {
    local($_) = @_;
    tr/A-Z/a-z/;
    return $_;
}

$constants_decl_code = '';

open FEATURESDEF, $ARGV[1] or
  die "open ($ARGV[1]): $!";

while (<FEATURESDEF>) {
  chop;				# strip record separator
  
  if (/^[^\#]/) {
    &parse_features_def ($_);
  }
}

close FEATURESDEF;

sub parse_features_def {
  local($line) = @_;
  @line_fields = split(/\|/, $line, 9999);
  $retval = $line_fields[1];
  $element_def = $line_fields[3];
  $feature = $line_fields[2];
  $param_def = $line_fields[4];

  $orig = $feature;
  $feature =~ s/^@//;
  $space = $feature;
  $space =~ s/./ /g;

  $constants_decl_code .= sprintf
    (qq[\#define %-40s %d\n], 'GLIBTOP_CMND_'.&toupper($feature),
     ++$feature_count);

  $features{$feature_count} = $feature;
}

chop $constants_decl_code;

$auto_gen_comment = sprintf
  (qq[/*\n * This file is automatically generated.\n * Please modify `command.pl' and `command.h.in'.\n */]);

open COMMAND, $ARGV[2] or
  die "open ($ARGV[2]): $!";

while (<COMMAND>) {
  chop;

  s/^\s*\@\@GLIBTOP_COMMAND_CONSTANTS\@\@\s*$/$constants_decl_code/;

  s/^\s*\@\@AUTOGEN_COMMENT\@\@\s*$/$auto_gen_comment/;
} continue {
  print $_;
}

close COMMAND;
