#! /usr/bin/perl -w
# looparound <Perlcode>
#
# Checks Perlcode, and if a Perl source, finds the first input
#  statement "$xxx = <STDIN>, to locate its assigned variable.
#  Surrounds the source with:
#    while (1) {
#      ...
#    if ($xxx eq ".") {last;}
#    }
#  And writes the new source to PerlcodeL
#
die "No code file given" unless (defined($ARGV[0]) && -e $ARGV[0]) ;
$code = $ARGV[0];
open (C, "<$code");
$line1 = <C>;
$inid = "";  #flags no < > found
if (substr($line1,0,2) eq "#!" && $line1 =~ /perl/) { # probably perl code
  ALL:
  while ($line = <C>) { #search for first input statement
    if ($line =~ /(\$.+)=\s*<STDIN>/) {  #capture the identifier
#print "var |$1| in |$line|\n";  #debug
      $inid = $1;
      last ALL;
    }
  }
}
close C;
if ($inid) { #OK to rewrite code
  open (C, "<$code");
  open (D, ">$code"."L");
  $line = <C>;
  print D $line;
  print D "\$| = 1;\n";
  print D "while (1) {\n";
  while ($line = <C>) {
    print D $line;
  }
  print D "if ($inid eq '.') {last;}\n}\n";
  close C;
  close D;
}
