#!/bin/perl -w
# Do note: if $COLLAPSE_DUPLICATES is set, only consecutive same
# numbers will be collapsed if $RETAIN_ORDER is set.
#
my $COLLAPSE_DUPLICATES = 1;
my $RETAIN_ORDER = 0;

$z = format_number_list(3, 3, 3, 3, 3);

sub expand_number_list {
    my @nums;

    for (split(', ', $_[0])) { 
	if (s/^(-?\d+)-(-?\d+)/$1\.\.$2/) {  # (\d) for negative ranges...
	    push @nums, eval($_);
	} else { 
	    push @nums, $_;
	}
    }

    return join ", ", @nums;
}

sub format_number_list {
    print "IN: ", join(", ", @_), "\n" if $DEBUG;
    my @numbers = @_;
    my ($nums, $left, $right);

    # sort? collapse duplicates?  
    @numbers = sort { $a <=> $b } @numbers
	unless $RETAIN_ORDER;
    if ($COLLAPSE_DUPLICATES) { 
	for ( my $i = 0; $i < $#numbers; $i++) {
	    splice @numbers, $i, 1 if $numbers[$i] == $numbers[$i+1];
	}
    }    

    # without the ,1 extra list member, the last element of @numbers
    # remains in $right.  Either the outermost else block must be
    # duplicated outside the for loop, or an extra element must used
    # to "flush" things out, at the cost of trimming the trailing
    # comma that results.    

    for (@numbers, 1) { 
	$left = $right = $_ unless defined $left;
	if ($_ == $right) { 
	    $right++ ;
	} else { 
	    $right--;
	    if ($left == $right) { 
		$nums .= "$left, ";
	    } else { 
		$nums .= "$left-$right, ";
	    } 
	    $left = $_;
	    $right = $left+1;
	}
    }

    $nums =~ s/, $//;
    $nums;
}


__END__

--Chan
