#!/usr/bin/perl
#
# Expands ranges of indices. The arguments are given on the command line
# and the expanded expression is written on standard output. For instance,
# "rgind foo[1..2,bar,13..15]" would yield
#
#    foo[1,bar,13] foo[1,bar,14] foo[1,bar,15]
#    foo[2,bar,13] foo[2,bar,14] foo[2,bar,15]
#
# Ranges can have negative limits as well. If no argument is given,
# the standard input is used.
#
# Written by T. Bousch, and placed in the Public Domain.

$sep = "";
if ($#ARGV >= 0) {
	# Expand the arguments on the command line
	foreach $_ (@ARGV) {
		&expand_name($_);
		print "\n";
	}
}
else {
	# No arguments, read expressions on standard input, one per line
	select STDIN;  $|=1; 
	select STDOUT; $|=1;
	while (<STDIN>) {
		chop;
		&expand_name($_);
		print "\n";
	}
}
exit 0;

sub expand_name {
	local($name) = @_;
	local($i, $before, $after);
	if ($name =~ /(-?\d+)\.\.(-?\d+)/) {
		$before = $`;
		$after  = $';
		foreach $i ($1 .. $2) { &expand_name($before.$i.$after); }
	}
	else { print "$sep$name"; $sep = " "; }
}
