#!/bin/csh

if( "$1" == "-h" ) then
	echo "usage: lsruns [-h] ["'"'"PATTERN"'"'" ...]" >> /dev/stderr
	echo -n "NOTE : patterns containing the wildcards * or ?" >> /dev/stderr
	echo " must be enclosed in "'"'"..."'"' >> /dev/stderr
	exit 1
endif

if( $#argv < 1 ) then
	set patterns = "*"
else
	set patterns = ( $argv[1-]:q )
endif
set lspatterns = ""
foreach pattern ( $patterns:q )
	set lspatterns = "$lspatterns p.$pattern"
end

if( $?LSRUNS_COLS ) then
	set cols = $LSRUNS_COLS
else
	set cols = 6
endif

if( $?LSRUNS_FW ) then
	set width = $LSRUNS_FW
else
	set width = 10
endif

set pushdsilent

pushd data
set files = `sh -c "ls $lspatterns 2>/dev/null | sort -f"`
if ( $#files == 0 ) then
	echo "lsruns: no matching runs" >> /dev/stderr
	exit 1
endif
popd

set filenum = $#files
@   rows    = $filenum / $cols

@   fnum    = $rows * $cols
if( $fnum < $filenum ) then
	@ rows = $rows + 1
endif

set row = 1
set col = 0
while( $row <= $rows )
	@ idx = $row + $rows * $col
	if( $idx <= $filenum ) then
		printf "%-${width}s" " $files[$idx]:e"
	endif
	@ col = $col + 1
	if( $col >= $cols ) then
		printf "\n"
		set col = 0
		@ row = $row + 1
	endif
end

if( $col > 1 ) then
	printf "\n"
	set col = 1
endif
