#!/usr/bin/perl -n
# converts labelled do-loops to loops using enddo.
# usage do.pl input-file > output-file
#
# Print comments without processing. 
#
(/^[cC]/) && (print);
(/^[cC]/) && (next);
#
# Don't print empty lines.
#
(/^[ \t\n]+$/) && (next);
#
# Translate every line into a lower case.
#
$_=~ tr/A-Z/a-z/;
#
# change all \w continuation sysmbols to $ .
#
$_=~ s/^(\s{5,5})\w/$1\$/;
#
# initialize stack count.
#
($.==1)&&($i=-1);
#
# If the last statement of the cycle is finished,
# print "end do"s for the number of cycles put on the stack so far. 
#
if(!/^\s{5,5}\S/){
# print "ENDDO $enddo\n";
 while($enddo){
   print "      end do\n";
   $enddo--;
 }
}
#
# Consider lines starting with "do".
#
if (/(^[\s\d]+do[\s\t]+)/){
 chop;
 @loopspec = split(/\s+/, $');
 $labels[++$i]=shift(@loopspec);
#  print "LOOP STACK", "$i,  @labels \n";
 print $1,join(' ', @loopspec),"\n";
 next;
}
print;
#chop;
split;
#
# Find the start of last cycle operator to place "end do" after it.
# 
while ($i>=0 and $_[0]  eq $labels[$i]){
 $enddo++; 
 $i--;
}
