#!/usr/bin/perl
# Copyright 2000-2003 Vlado Keselj www.cs.dal.ca/~vlado
#
# Justify text, left align, ragged right.

use strict;
use vars qw($VERSION);

$VERSION = sprintf "%d.%d", q$Revision: 1.4 $ =~ /(\d+)/g;

use Getopt::Long;

my($par, $keepnl, $linelen, $help, $version);
$linelen = 72;

help() unless
    GetOptions('keep-nl'    => \$keepnl,
               'line-len=i' => \$linelen,
	       'help'       => \$help,
	       'version'    => \$version);

sub version {
    print $VERSION, "\n";
    exit(1);
}

help()    if $help;
version() if $version;

while (<>) {
    if ($keepnl or $par =~ /\n\s*\n$/) {
	$par =~ /(\n*)$/;
	my $paragraphend = $1;
	print join("\n",  &justify($linelen, $par));
	print $paragraphend;
	$par = '';
    }
    $par .= $_;
}

if ($par) { foreach my $l ( &justify($linelen, $par) ) { print "$l\n" } }

sub justify($@) {
    my $width = shift;
    my ($p, $r, @ret);
    while (@_) { $p.= " ". shift }

    $p =~ s/^\s+//; $p =~ s/\s+/ /g; $p =~ s/\s*$/ /;
    while ($p) {
	$p =~ / /;
	$r = $`; $p = $';
	while ($p) {
	    $p =~/ /;
	    if (length("$r $`") <= $width) {
		$r .= " $`"; $p = $';
	    } else { last; }
	}
	push @ret, $r;
    }
    return @ret;
}

sub help {
    print <<EOF;
Usage: $0 [options] [files]
Justify text, left align, ragged right.

End of paragraph is a double new line.

Options:
--keep-nl       Keep existing new-lines.
--line-len=N    Line length.
--help		Show this help.
--version	Show version.

The options can be shortened to their unique prefixes and
the two dashes to one dash.  No files means using STDIN.
EOF
    exit(1);
}


exit 0;

__END__
=head1 NAME

justify - Justify text, left align, ragged right.

=head1 SYNOPIS

   justify [input files]

=head1 DESCRIPTION

This script left-justifies the input text into 72-width rows by
default, or as specified by the option line-len.

=head1 PREREQUISITES

Getopt::Long

=head1 SCRIPT CATEGORIES

Text

=head1 README

Justifies text, left align, ragged right.

=head1 COPYRIGHT

Copyright 2003 Vlado Keselj F<http://www.cs.dal.ca/~vlado>

This script is provided "as is" without expressed or implied warranty.
This is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

The latest version can be found at F<http://www.cs.dal.ca/~vlado/srcperl/>.

=cut
