#!/usr/bin/perl

# Input: output of alicat.pl (preferably with -v)

my $lineLen = shift @ARGV;

my @pfx;
my @lines;
while (<>) {
    chomp;
    s/ +$//;
    my $kMax = length($_)-1;
    if ($kMax < 0 && !@pfx) {
	@pfx = @lines;
	@lines = ();
    }
    for (my $k=0; $k<=$kMax; $k++) {
	if ($k > 0 && !$lines[$k]) {
	    $lines[$k] = ' ' x length($lines[0]);
	}
	$lines[$k] .= substr($_,$k,1);
    }
    for (my $k=$kMax+1; $k<=$#lines; $k++) {
	$lines[$k] .= ' ';
    }
    if (length($pfx[0]) + length($lines[0]) >= $lineLen) {
	printLines();
	@lines = ();
    }
}
printLines();

sub printLines {
    my $lastBlank = 1;
    foreach my $k (0 .. $#lines) {
	unless ($pfx[$k]) {
	    $pfx[$k] = ' ' x length($pfx[1]);
	}
	my $line = "$pfx[$k]$lines[$k]";
	$line =~ s/ +$//;
	if ($line =~ /[^ |]/) {
	    print "$line\n";
	    $lastBlank = 0;
	} else {
	    print "\n" unless ($lastBlank);
	    $lastBlank = 1;
	}
    }
}

