#!/usr/local/bin/perl

sub printTeX
{ s/`([@\w]+)\s*<->(\w+)/\\index{\l\1,\\both{\2}}`\1 \\both{\2}/g;
  s/`([@\w]+)\s*<-(\w+)/\\index{\l\1,\\get{\2}}`\1 \\get{\2}/g;
  s/`([@\w]+)\s*->(\w+)/\\index{\l\1,\\send{\2}}`\1 \\send{\2}/g;
  s/<->(\w+)/\\both{\1}/g;
  s/<-(\w+)/\\get{\1}/g;
  s/->(\w+)/\\send{\1}/g;
  s/([a-z]\w+)\/((\d+|\[\d+(-|,)\d+\]))/\\index{\l\1\/\2}\\predref{\l\1}{\2}/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/(\\file{[^}]*)~([^}]*})/\1\\Stilde\2/g;
  s/(\\file{[^}]*)\$([^}]*})/\1\\Sdollar\2/g;

# Prolog special arguments ...

  s/{#!}/{\\Sexe}/g;
  s/{!}/{\\Scut}/g;
  s/{,}/{\\Scomma}/g;
  s/{->}/{\\Sifthen}/g;
  s/{\*->}/{\\Ssoftcut}/g;
  s/{\.}/{\\Sdot}/g;
  s/{;}/{\\Ssemicolon}/g;
  s/{<}/{\\Slt}/g;
  s/{=}/{\\Seq}/g;
  s/{=\.\.}/{\\Suniv}/g;
  s/{=:=}/{\\Saeq}/g;
  s/{=<}/{\\Sle}/g;
  s/{==}/{\\Sequal}/g;
  s/{=@=}/{\\Sstructeq}/g;
  s/{\\=@=}/{\\Sstructneq}/g;
  s/{=\\=}/{\\Sane}/g;
  s/{>}/{\\Sgt}/g;
  s/{>=}/{\\Sge}/g;
  s/{@<}/{\\Stlt}/g;
  s/{@=<}/{\\Stle}/g;
  s/{@>}/{\\Stgt}/g;
  s/{@>=}/{\\Stge}/g;
  s/{\\\+}/{\\Snot}/g;
  s/{\\=}/{\\Sne}/g;
  s/{\\==}/{\\Snequal}/g;
  s/{\^}/{\\Shat}/g;
  s/{\|}/{\\Sbar}/g;
  s/{\*}/{\\Stimes}/g;
  s/{\*\*}/{\\Spow}/g;
  s/{\+}/{\\Splus}/g;
  s/{-}/{\\Sminus}/g;
  s/{\/}/{\\Sdiv}/g;
  s/{\/\/}/{\\Sidiv}/g;
  s/{\/\\}/{\\Sand}/g;
  s/{<<}/{\\Slshift}/g;
  s/{>>}/{\\Srshift}/g;
  s/{\\}/{\\Sneg}/g;
  s/{\\\/}/{\\Sor}/g;
  s/{\$}/{\\Sdollar}/g;
  s/{\?}/{\\Squest}/g;
  s/{:}/{\\Smodule}/g;
  s/{:-}/{\\Sneck}/g;
  s/{\?-}/{\\Sdirective}/g;
  s/{-->}/{\\Sdcg}/g;
  s/{~}/{\\Stilde}/g;
  s/{%}/{\\Spercent}/g;
  s/{#}/{\\Shash}/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;
}
