#!/usr/local/bin/perl -w
use strict;

##  Fix man macros so tkman2pod accepts it
##  (deduced from diff of manpages to tk402)


my @options;
my $inSTDOPT;
my $firstOPTDEF;

while (<>)
 {
  if ($. == 1)
   {
    my ($leaf) = $ARGV =~ m#/([^/]+)$#;
    my $new    = "man/$leaf";
    close(FILE) if (defined fileno(FILE));
    open(FILE,">$new") || die "Cannot open $new:$!";
    print STDERR "$ARGV -> $new\n";
   }

### 0 ### strip change bars

  $_ = '' if /^\.V[ES]/;

### 1 ###   man with CS|E is wrong IMO so maybe do it perlmanently?

  s/^\.CS/.DS C/;
  s/^\.CE/.DE/;

### 2 ###

  if (/^\.SE/)
    {
       $inSTDOPT = 0;
       $_ = ".fi\n.LP\n";
    }
  if ($inSTDOPT)
    {
	@options = map { "\\fB$_\\fR" } split; 
	$_ = join("\t", @options) . "\n";
    }
  if (/^\.SO/)
    {
       $inSTDOPT = 1;
       $_ = ".LP\n.nf\n.ta 4c 8c 12c\n";
    }

### 3 ####

  if (/^\.OP/)
    {
       chomp;
       @options = split;
       shift @options;
       die join("|",scalar(@options),@options) ."| not 3 opt defs in: #$_#"
		unless (@options == 3 or @options == 5);
       $_ = ($firstOPTDEF ? "" : ".ta 8c\n" );
       $firstOPTDEF = 1;
       if (@options == 3)
         {
            $_ .= ".LP\n.nf\n" 
                . "Name:\t\\fB" .  $options[1] . "\\fR\n"
                . "Class:\t\\fB" . $options[2] . "\\fR\n"
                . "Switch:\t\\fB" .$options[0] . "\\fR\n"
	        . ".fi\n.IP\n";
         }
       else
         {
	    die "no or in opt def: $_\n" unless $options[1] eq 'or';
	    $options[0] =~ s/^\"//;
	    $options[2] =~ s/\"$//;
            $_ .= ".LP\n.nf\n" 
                . "Name:\t\\fB" .  $options[3] . "\\fR\n"
                . "Class:\t\\fB" . $options[4] . "\\fR\n"
                . "Switch:\t\\fB" .$options[0] . "\\fR\n"
		. "Alias:\t\\fB" . $options[2] . "\\fR\n"
	        . ".fi\n.IP\n";
	 }
      
    }

#########

  print FILE $_;

  if (eof)
   {
    close(FILE) if (defined fileno(FILE));
    $. = 0;
    die "no closing SE for SO found" if $inSTDOPT;
    $firstOPTDEF = 0;
   }
 }

