#!/usr/bin/perl
use strict;

if (@ARGV == 0 or $ARGV[0] eq "--help")
{
  print <<USAGE;
Usage: compare TEXT CORPUS1 CORPUS2 [CORPUS3]...
Compression-based classification.  Compare a TEXT against several CORPI of
text and print the CORPUS that the TEXT resembles most.  TEXT and CORPI may be
paths to individual text files or wildcard patterns.
USAGE
  exit;
}

sub size_when_zipped
{
  my $file_patterns = join ' ', @_;
  return `cat $file_patterns | gzip | wc -c`;
}

sub bytes_added_by_text
{
  (my $corpus, my $text) = @_;
  return size_when_zipped( $corpus, $text ) - size_when_zipped( $corpus );
}

sub best_of
{
  (my $metric, my @option) = @_;
  my $best_so_far = shift @option;
  foreach (@option)
  {
    $best_so_far = $_ if &$metric( $_ ) > &$metric( $best_so_far );
  }
  return $best_so_far;
}

die "Not enough arguments." if @ARGV < 3;

(my $text, my @example_texts) = @ARGV;

my $resembles_text = sub { -1 * bytes_added_by_text( $_[0], $text ) };

print best_of( $resembles_text, @example_texts ) . "\n";
