#!/usr/bin/perl

$^W=1;
use strict;
use Getopt::Long;

#vi(1) se tabstop=4

Getopt::Long::Configure (
	"posix_default", # start with POSIX (compatible) defaults
	"bundling", # then tweak as seems fitting
);

my $help=undef;
my $case=undef;
my $usage=undef;
my $case=undef;

GetOptions (
	"help|h|?" => \$help,
	"case|c" => \$case,
) or die "$0: bad option(s), aborting\n${usage}aborting";

my $usage="usage: $0 [--help|-h|-?] [--case|-c] [file ...]";
my $helptext=<<""
$usage
	--help|-h|-?
		Help - provide some basic usage information, overrides other
		options.
	--case|-c
		also apply case conversions
	file - file(s) to process (defaults to stdin)

;
$usage="$usage\n";

# detabify
$usage=~s/\t/    /og;
$helptext=~s/\t/    /og;

if($help){
	print "$helptext" or
		exit 1;
	exit 0;
};

while(<>){
	chomp;
										# generally (there are exceptions)
	s/([.!?])(?![]) .!?]|$)/\1  /go;	# two spaces after sentence end
	s/([,;])(?![]) ,;]|$)/\1 /go;		# space after , or ;
	s/&(?! |&|$)/& /go;					# space after &
	s/([^ &])&/\1 &/go;					# space before &
	s/([[:alpha:]][.!?]*)\(/\1 (/go;	# space before (
	s/\)([[:alpha:]])/) \1/go;			# space after )
	s/( |^|^~)(i)(m)(?=[.!? ]|$)/\1\2'\3/igo;	# im --> i'm
	s/( |^|^~)(don)(t)(?=[.!? ]|$)/\1\2'\3/igo;	# dont --> don't

	if($case){
										# if we're doing case conversions ...
										# generally (there are exceptions)
		s/[[:upper:]]/\l$&/go;						# to lowercase
		s/(^|[.!?] +)[[:lower:]]/\U$&/go;			# sentence start upper
		s/( |^|^~)i(?=[.!? ]|$)/\1I/go;				# i --> I
		s/( |^|^~)i'(ll|m|ve)(?=[.!? ]|$)/\1I'\2/go;# i'll/i'm/i've --> I'll/I'm/I've
	};

	print "$_\n";
};
