# program to add line number as comments before the start of every
# line in c/c++ programs. 
# started : 23/3/2004 10.38 pm
# ended   : 24/3/2004  9.31 pm

$line = 1;
$ifile = $ARGV[0];

if (($ifile cmp "") == 0)
 {
  print "\n Usage : perl lineNum.pl <inputFile>" ;
  print "\n Output will be written to o<inoutFile> \n";
  exit ();
 }

$ofile = "o".$ifile;
$insideComment = 0;


 if(open(IFILE,"<".$ifile))	 # open the i/p file in Read mode
  {
  if (open(OFILE,">".$ofile))
   {
   while(<IFILE>) 		 # while i/p file exists
    {
       # Takes care of block comments not to nest the /* ... */
       if ($insideComment)
         {
          print OFILE " * Line ";
         }
       else
         {
          print OFILE "/* Line ";
         }

        printf OFILE ("%3d", $line);

       if ($insideComment)
         {
          print OFILE " *  ";
         }
       else
         {
          print OFILE " */ ";
         }

        print OFILE $_ ; # Do not use printf as it interprets %fmt
                         # specifier present in the program

      if ($_ =~ m/\/\*/)   {  $insideComment = 1; }
      if ($_ =~ m/\*\//)   {  $insideComment = 0; }

     $line ++; # increment line number counter
    }
   }
   else
   {
    print "Cannot open output file ". $ofile . "\n";
   }
  }
  else
   {
    print "Cannot open input file ". $ifile . "\n";
   }

print "\n Output written to ", $ofile , "\n";
