#! /opt/bin/perl5 -w
#
## Author: George Pereira
## Date: 25th November 2002
#

use strict;

our ($G_sort, $G_diff);
## $G_sort: 0 - Don't sort, 1 - Ascending, 2 - Descending
## $G_diff: The difference between the numbers

## $G_sort: 0 by default
## $G_diff: 1 by default

my ($str) = &format_number_list(1,2,4,5,5,6,7,13,13,24,24,25,26,27);
print "NUM($str)\n";
print "ARRAY(" . join("|", &expand_number_list($str)) . ")\n";

sub format_number_list
	{
	my (@arr, @res, @elements, $diffnum);
	(@arr) = @_;
	$G_sort = 0 if (!defined $G_sort);
	$G_diff = 1 if (!defined $G_diff);
	@arr = sort {$a <=> $b} @arr if ($G_sort == 1);
	@arr = sort {$b <=> $a} @arr if ($G_sort == 2);
	$diffnum = ($G_sort == 2) ? 0 - $G_diff : $G_diff;

	for (my $cnt = 0; $cnt <= $#arr; $cnt++)
		{
		my ($preval, $nextval);
		($preval, $nextval) = map { $arr[$_]; } (($cnt - 1),($cnt + 1));
		if (($preval + $diffnum) != $arr[$cnt])
			{
			push (@res, &negative($arr[$cnt]));
			}
		elsif ($cnt == $#arr || (($arr[$cnt] + $diffnum) != $nextval))
			{
			$res[$#res] .= "-" . &negative($arr[$cnt]);
			}
		}
	return join(", ", @res);
	}

sub negative
	{
	my ($num);
	($num) = @_;
	return ($num < 0) ? "($num)" : $num;
	}

sub expand_number_list
	{
	my ($str, @res, @tmp);
	($str) = @_;
	@tmp = split(/, */, $str);
	foreach my $val (@tmp)
		{
		$val =~ s/[()]//g;
		if ($val =~ /^(-?[0-9]+)$/)
			{
			push (@res, $1);
			}
		elsif ($val =~ /^(-?[0-9]+)-(-?[0-9]+)/)
			{
			if ($1 <= $2)
				{
				push (@res, ($1 .. $2));
				}
			else
				{
				push (@res, reverse ($2 .. $1));
				}
			}
		}

	return @res;
	}

