#
open(F,$ARGV[0]) || die "Cannot open $ARGV[0]: $!";
my $gotnml = 0;
my $varlist = '';
while(my $iline = <F> ) {
      # Start processing loop (checks are case and whitespace independent)
      #
      # 1. If a namelist block is open then
      #
      if ( $gotnml == 1 ) {
         #
         # 2. If leading ampersand: this line is part of a continuation
         #
         if ( $iline =~ /^\s*&/) {
           ($ivars2 = $iline) =~ s/(^\s*&\s*)([^&!]*)(.*)/\2/;
           chomp($ivars2);
           $ivars2 =~ s/^\s+//; $ivars2 =~ s/\s+$//;
           my $i1 = index($iline, "&");
           my $i2 = index($iline, "&", $i1+1);
           #
           # 3. If no trailing ampersand: reached the end of a continuation
           #
           if ( $i2 == -1 ) {
             print "&".$iargs."\n";
             @allvars = split(',',$varlist.$ivars2);
             foreach my $v (@allvars) { 
               $v =~ s/^\s+|\s+$//g;
               print "  ".$v." = \n"; 
             }
             print "/\n";
             $gotnml = 0;
             $varlist = '';
           #
           # 4. Else trailing ampersand: Append to list and expect more
           #
           } else {
             $varlist = $varlist.$ivars2;
           }
         #
         # 5. Else no leading ampersand: it must have been a single line declaration
         #
         } else {
           print "&".$iargs."\n";
           @allvars = split(',',$varlist);
           foreach my $v (@allvars) { 
             $v =~ s/^\s+|\s+$//g;
             print "  ".$v." = \n"; 
           }
           print "/\n";
           $gotnml = 0;
           $varlist = '';
           #
           # 6. But better check if this line starts a new declaration
           #
           if ( $iline =~ /^\s*namelist\s*\//i) {
             ($iargs = $iline) =~ s/(^\s*namelist\s*\/\s*)([A-Z,a-z,0-9,_]*)(.*)/\2/i;
             chomp($iargs);
             $iargs =~ s/^\s+//; $iargs =~ s/\s+$//;
             ($ivars = $iline) =~ s/(^\s*namelist\s*\/\s*[A-Z,a-z,0-9,_]*\s*\/)([^&!]*)(.*)/\2/i;
             chomp($ivars);
             $ivars =~ s/^\s+//; $ivars =~ s/\s+$//;
             $gotnml = 1;
             $varlist = $ivars;
           }
         #
         }
      #
      # 7. Else if a namelist declaration is found
      #
      } elsif ( $iline =~ /^\s*namelist\s*\//i) {
         #
         # 8. Store the namelst name 
         #
         ($iargs = $iline) =~ s/(^\s*namelist\s*\/\s*)([A-Z,a-z,0-9,_]*)(.*)/\2/i;
         chomp($iargs);
         $iargs =~ s/^\s+//; $iargs =~ s/\s+$//;
         ($ivars = $iline) =~ s/(^\s*namelist\s*\/\s*[A-Z,a-z,0-9,_]*\s*\/)([^&!]*)(.*)/\2/i;
         chomp($ivars);
         $ivars =~ s/^\s+//; $ivars =~ s/\s+$//;
         $gotnml = 1;
         $varlist = $ivars;
         #
      #
      # 9. Else any other statement
      #
      } else {
         #
         # 10. Not a namelist statement so ignore
         #
      }
}
