#!/usr/bin/perl
# Join lines of a preformatted text. It keeps joining
# until the specified regexp is found in one line, in
# which case the complete line (including the one with
# the regexp) is output.

while(@ARGV and $ARGV[0] =~ /^-/) {
    $_ = shift @ARGV;
    last if /^--$/;
    if    (/^-r(.+)/)      {$REGEXP = qr/$1/ or 
                                die "BOGUS -r option: $1\n" ; exit ;}
    elsif (/^-R(.+)/)      {$IGNORE = $1 ;}
    elsif (/^-t(.*)$/)     {$TRANSLATE = qr/$1/ or 
                                die "BOGUS -t option: $1\n" ; exit ;}
    elsif (/^-d$/)         {$DELETE = 1 ;}
    elsif (/^-D$/)         {$DELETE_ALL = 1 ;}
    else { error_exit() ;}
}

$REGEXP ||= "." ;
$start = 1 ;
$line = "" ;

LINE:
    while(<>) {
        if($IGNORE and /$IGNORE/o) {
            print $_ ;
            next LINE ;
        }
        chomp ;
        if (/$REGEXP/) {
            if ($DELETE_ALL or not($start) and $DELETE) {
                s/$REGEXP/$TRANSLATE/g ;
            };
            $start = 0 ;
            $line .= $line ? " $_" : $_ ;
            next LINE ;
        } else {
            print $line . "\n" if $line ;
            print $_ . "\n" ;
            $line = "" ;
            $start = 1;
        }
}
# end if there is anything left
print $line if $line ;
