##
# Copyright (c) 2008 Health Market Science, Inc
##
package _TMP;
use strict;
use warnings;
our $CVS_ID = '$Id: emacs-utils.el,v 1.82 2008/07/11 13:35:40 kburton Exp $'; #'
our $VERSION = ( qw$Revision: 1.82 $ )[1];

sub run {
  my($self) = @_;

  my $cmd = shift @ARGV;
  my %dispatch = (map { $_ => $_ } qw(encode unencode));
  unless ($cmd && exists $dispatch{$cmd}) {
    die "Error: unrecognized command:'$cmd', try one of (" . join(", ", sort keys %dispatch). ")";
  }
  $self->$cmd(@ARGV);
}

sub openFile {
  my($self,$file,$mode) = @_;
  $mode ||= '<';
  my $fh;
  unless (open $fh, $mode, $file) {
    die "Error opening file: $file : $!\n";
  }
  return $fh;
}

sub readFile {
  my($self,$file) = @_;

  local $/ = undef;
  my $fh = $self->openFile($file);
  my $data = <$fh>;
  return $data;
}

sub encode {
  my($self,$input,$output) = @_;
  unless (-e $input) {
    die "Error: input: $input does not exist!\n";
  }

  my $out = $self->openFile($output,">");

  my @chrs = split //, $self->readFile($input);
  print "There are ", scalar(@chrs), " characters\n";
  my $ch = shift @chrs;
  my $cnt = 1;
  while (@chrs) {
    my $next = shift @chrs;
    if ($next eq $ch) {
      ++$cnt;
      next;
    }
    print $out $cnt, $ch;
    $ch = $next;
    $cnt = 1;
  }
  print $out $cnt, $ch;
  close $out;
}

sub unencode {
  my($self,$input,$output) = @_;
  unless (-e $input) {
    die "Error: input: $input does not exist!\n";
  }

  my $str = $self->readFile($input);
  my $out = $self->openFile($output,">");

  while (length $str) {
    unless ( $str =~ s/^(\d+)(\D+)// ) {
      die "Error: invalid format in string (did not start with number)? : " . substr($str,0,10). "...";
    }
    my($cnt,$chr) = ($1,$2);
    print $out $chr x $cnt;
  }
  close $out;
}

1;

_TMP->run;

