
package TestFormat;
use strict;

BEGIN {
  open SAVE_STDOUT, ">&STDOUT" or die $!;
  open STDOUT, ">", "/dev/null" or die $!;
  open STDIN, "<", "/dev/null" or die $!;
  open 'main::DATA', "<", "/dev/null" or die $!;
}

END {
  my $N = 1;
  my $TEST_THESE = $ENV{CLASS} || "Basic";
  my $DIE_OK = $ENV{DIE_OK};
  open STDOUT, ">&SAVE_STDOUT" or die $!;
TEST:
  while (<DATA>) {
    chomp;

    my @a = eval { main::expand_number_list($_) };
    if ($@) {
      chomp $@;
      print "not ok $N # Died: $@\n";
      next;
    }
    if (my $ERR = array_mismatch(\@a, [mjd_expand($_)])) {
      print "not ok $N # $ERR\n";
    } else {
      print "ok $N\n";
    }
    $N++;
  }
}

sub mjd_expand {
  my $s = shift;
  my @result;
  for (split /,\s+/, $s) {
    if (/^(\d+)-(\d+)$/) {
      push @result, $1 .. $2;
    } elsif (/^(\d+)$/) {
      push @result, $1;
    } else {
      warn "Bad word '$_' in '$s'; ignoring\n";
    }
  }
  @result;
}

sub array_mismatch {
  my ($a, $x) = @_;
  my ($al, $xl) = (scalar @$a, scalar @$x);
  return "length $al should be $xl" unless $al == $xl;
  for my $i (0 .. $#$a) {
    return "Element $i ($a->[$i]) should be $x->[$i]"
      unless $a->[$i] == $x->[$i];
  }
  return;
}

"Cogito, ergo sum.";
__DATA__
1
1, 3
1-2
1, 2
1-3
1-3, 5, 8, 13
1, 2, 4-7, 9, 13, 24-27
1-2, 4-7, 9, 13, 24-27
1, 17-18, 99
1-3, 6, 10-14, 18, 90-92, 100
