#!/usr/local/gnu/bin/perl

# Purpose:
#  Wrap lines of a Fortran code at 72 columns, stripping off
#  trailing comments along the way.
#  Print cpp commands (lines starting with `#') without modification.


while(<>) {
    # remove the trailing linefeed so it doesn't
    # get treated as a regular character, then put it back.
    chomp ;
    # output a cpp line as-is; strip all others
    if ( /^\s*\#/ ) {
        print $_,"\n" ;
    } else {
        print &strip72(),"\n" ;
    }
}

sub strip72 {
    my $e = index($_,"!") ;  #find comment character
    if ( $e >= 0 ) { 
        # possibly a trailing comment

        # look for quote character that delimints a string
        my $q = index($_,"'") ;

        if ( $q >= 0 and $q < $e ) { 

            # comment after open quote, look for close quote
            while( ($q = index($_ ,"'" ,$q+1 )) > -1 ) {
                if( $e < $q ) {
                    # exclamation point inside string, look for next one
                    $e = index($_ ,"!" ,$q+1) ;
                    # done if no more
                    if ( $e < 0 ) { last ; }
                }
                # look for next open quote
                $q = index($_,"'",$q+1) ;
                # if no next open quote or it is after the exclamation
                # strip the trailing comment
                if( $q < 0 or $q > $e ) {
                    $_ = substr($_,0,$e) ;
                    last ;
                }
            }
        } else {
            # quote after comment so strip the comment
            $_ = substr($_,0,$e) ;
        }

    } #else # no exclamation so no comment

    # now break the line into 72 character pieces with continuations
    #[NOTE: some of the `substr' calls will generate Perl warnings.]
    my $out = substr($_,0,72) ;
    $_ = substr($_,72) ;
    while ( $_ ) {
        $out .= "\n     &" . substr($_,0,66) ;
        $_ = substr($_,66) ;
    }
    return $out ;
}
