#!/usr/local/bin/perl

sub printTeX
{ s/`([@\w]+)\s*<->(\w+)/\\index{\l\1,\\both{\2}}`\\classboth{\1}{\2}/g;
  s/`([@\w]+)\s*<-(\w+)/\\index{\l\1,\\get{\2}}`\\classget{\1}{\2}/g;
  s/`([@\w]+)\s*->(\w+)/\\index{\l\1,\\send{\2}}`\\classsend{\1}{\2}/g;
  s/<->(\w+)/\\both{\1}/g;
  s/<-(\w+)/\\get{\1}/g;
  s/->(\w+)/\\send{\1}/g;
  s/(\s+|^)([a-z]\w+)\/((\d+|\[\d+(-|,)\d+\]))/\1\\index{\2\/\3}\\predref{\2}{\3}/g;
  s/(\w\.\w)\.(\s+[a-z])/\1.\\\2/g;
  s/(^|[^\w}\\])@(\w+)/\1\\index{@\2}\\objectname{\2}/g;
  s/<(\w[-~\w]*)>/\\bnfmeta{\1}/g;
  s/\\class{([<\\=>]*)}/\\verb!\1!/g;
  s/==>/\$\\longrightarrow\$/g;
  s/^((\\index{[^}]+})+) *$/\1%/;
  s/(\\index{[^}]*)\\index{[^}]*}([^}]*})/\1\2/g;
  s/(\\class(get|send|both){)\\index{[^}]*}/\1/g;

  print;
}


sub expandTabs
{ while ( ($i = index($_, "\t")) != $[-1 )
  { $nspaces = 8 - $i % 8;
    for( $spaces="", $i=0; $i<$nspaces; $i++ )
    { $spaces .= " ";
    }
    s/\t/$spaces/;
  }
}


sub
expandSpecials
{ s/\^/\\verb!^!/g;
  s/\|/\\verb!|!/g;
}


sub printCode
{ print;
  while (<ARGV> )
  { &expandTabs;
    print;
    if ( /\\end{(code|verbatim)}/ )
    { return;
    }
  }
}


sub printPceCode
{ $line = 0;
  print;
  while (<ARGV> )
  { $line++;
    &expandTabs;
    if ( /\\end{pcecode}/ )
    { print;
      return;
    }
    chomp;
    print "\\lineno{$line}\\verb`$_`\n";
  }
}


sub skiptonext
{ while (<ARGV>)
  { if ( ! /^\s*$/ )
    { return;
    }
    last;
  }
  while (<ARGV>)
  { if ( ! /^\s*$/ )
    { return;
    }
  }
}

#	MAIN PROGRAM

while (<>)
{ while ( /\\begin{pcecode}/ )
  { &printPceCode;
    print "\n\\noindent\n";
    &skiptonext;
  } 
  while ( /\\begin{(code|verbatim)}/ )
  { &printCode;
    print "\n\\noindent\n";
    &skiptonext;
  }
  &printTeX;
}
