#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Std;

$Getopt::Std::STANDARD_HELP_VERSION = 'true';

my $help = q{Usage: wczip [OPTIONS] FILE [FILE] . . .
Replace every string of contiguous nonwhitespace characters in a
file with a single letter.

    -c CHAR    specify the character to be used for substitutions
               (defaults to the lowercase letter s)

    -o NAME    specify the name of the output file to be used
               (defaults to the name of the input file with the
	       .wcz extension added to the end)

    -v         verbose output

    --help     display this help information and exit

    --version  print version information to STDOUT and exit
};

my $version = 'wczip 0.0.2
Copyright (C) 2007 Chad L. Perrin (Author)
You may distribute copies of this software under the terms of the
CCD CopyWrite license <http://ccd.apotheon.org>.

To the extent permitted by law, no warranty, express or implied,
applies to this software.
';

our($opt_c, $opt_o, $opt_v);
getopts('c:o:v');

$opt_c ||= 's';

my $text;

foreach my $filename (@ARGV) {
  open(my($fh_in), '<', $filename) || die $!;
  local $/;
  $text .= <$fh_in>;
  unless ($opt_o) {
    $opt_o = $filename . '.wcz';
    open my $fh_out, '>', $opt_o;
    transform();
    print $fh_out $text;
    close $fh_out;
    $opt_o = '';
    $text = '';
  }
  close $fh_in;

  print "including file: $filename\n" if $opt_v;
}

if ($opt_o) {
  transform();
  open(my $fh_out, '>', $opt_o) || die $!;
  print $fh_out $text;
  close $fh_out;
}

sub transform {
  $text =~ s/[\w[:punct:]]+/$opt_c/g;
  $text =~ s/^\s+//g;
  $text =~ s/\s+$//g;
  $text =~ s/\s+/ /g;
}

sub HELP_MESSAGE {
  print $help;
}

sub VERSION_MESSAGE {
  print $version;
}
