#!/usr/bin/perl -W
#
# Purpose:	make a source .c or .h file from a .m (mkplugin) file
# Usage:	mkplugin.pl File.{h|c} [Tag0 Tag1 ...]
#	File.h	Produce the file File.h from the file File.h.m.  Include
#		cut blocks labeled with any of the tags Tag0, Tag1, ...
#	File.c	Produce the file File.c from the file File.c.m.  Include
#		cut blocks labeled with any of the tags Tag0, Tag1, ...
# Example:	mkplugin.pl COUNTER.c debug	# include =debug blocks
#
# mkplugin.pl Commands:
#   o A line beginning with '=inc string' marks the beginning of a cut block.
#	The block ends at the first occurrence of a line beginning with
#	'=cut'.  A block is included (copied to the target file) if its tag
#	is in the command line.  The remainder of the =inc and =cut
#	line are treated as a comment.
#   o Blocks are not nested; i.e., a =inc terminates an unterminated =inc.
# History:
#   7/18/2005:	kenw, creation
#

use File::Basename;

sub isTag {
  my ($str) = @_;
###print "isTag:  str = $str\n";
  for ($i=0; $i<$ntags; $i++) {
    if ($tag[$i] eq $str)	{ return 1; }
  }
  return 0;
}

if ($#ARGV < 0)
{
  print "Usage: mkplugin.pl <File>.{c|h} [Tag0 Tag1 ...]";
  exit(1);
}
$file = $ARGV[0];
shift;

$ntags = 0;
while ($#ARGV >= 0) {	# get tags
  $tag[$ntags] = $ARGV[0];
  $ntags++;
  shift;
}

# debug
###for ($i=0; $i<$ntags; $i++) {
###  print "tag $i: $tag[$i]\n";
###}

$mfile = basename($file . ".m");

# debug
###print "mfile = $mfile\n";

open(MFILE, "<$mfile") or die ("Couldn't open $mfile");
open(OFILE, ">./$file") or die ("Couldn't open ./$file");

$inBlock = 0;
$keep = 1;
while ($line = <MFILE>) {
  @xxx = split(/\s+/, $line);
  $_ = $line;
  if (/^=inc/) {
    $str = $xxx[1];
    $inBlock = 1;
    if ( !isTag($str) )	{ $keep = 0; }
    next;
  } elsif (/^=cut/) {
    $inBlock = 0;
    $keep = 1;
    next;
  } else {
    if ($keep) { print OFILE $line; }
  }
}
close(MFILE);
close(OFILE);

