#!/usr/athena/bin/perl -w -i.bak
# Rewrite a C source file to #include <mit-copyright.h> and "config.h".
# The #includes are placed before any other CPP command except for
# tests for SABER and lint (which are used for rcsid).

use strict;

use vars qw( $skip $endif_lvl $eat_wspace $is_wspace $was_wspace );

$eat_wspace = $skip = $endif_lvl = 0;
$is_wspace = 1;

while (<>) {
  $was_wspace = $is_wspace;  $is_wspace = /^\s*$/;
  next if $eat_wspace && $is_wspace;

  ($eat_wspace = $was_wspace, $is_wspace = $was_wspace, next)
    if $skip && /^\#include\s*[<"](?:mit-copyright|config)\.h[">]/;

  $eat_wspace = 0;
  (print, next) if $skip;

  ($endif_lvl--, print, next) if $endif_lvl && /^\#endif/;
  ($endif_lvl++, print, next)
    if /^\#if\s*!\s*defined\s*\(?SABER\)?\s*&&\s*!\s*defined\(?lint\)?\s*$/
      || /^\#if\s*!\s*defined\s*\(?lint\)?\s*&&\s*!\s*defined\(?SABER\)?\s*$/
	|| /^\#ifndef\s+(?:SABER|lint)\s*$/;

  if (/^\#/) {
    (print, warn("Strange line (#endif): $_"), next) if $endif_lvl;

    print qq(\#include <mit-copyright.h>\n);
    print qq(\#include "config.h"\n);
    print qq(\n);
    $is_wspace = 1;
    $skip = 1;
    redo;
  }

  print;
} continue {
  if (eof) {
    die "oops!" if $endif_lvl;
    $eat_wspace = $skip = 0;
    $is_wspace = 1;
    print STDERR "$ARGV: done.\n";
  }
}
