#!/bin/csh

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

if( "$1" == "-f" ) then
	set force = 1
	shift
else
	set force = 0
endif

if( "$1" == "-i" ) then
	set interactive = 1
	shift
else
	set interactive = 0
endif

set files = ()
set runs  = ()

if( "$1" == "-ra" ) then
	shift
	if( $#argv == 1 ) then
		if( -f data/r.$1 ) then
			set files = \
				(data/d.$1 data/p.$1 data/q.$1 data/r.$1 data/l.$1)
			set runs  = $1
		endif
	else
		foreach lab ($argv[2-])
			set run   = `printf $1 $lab`
			if( -f data/r.$run ) then
				set files = \
					($files data/d.$run data/p.$run data/q.$run data/r.$run data/l.$run)
				set runs  = ($runs $run)
			endif
		end
	endif
else
	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
	set pushdsilent
	pushd data
	set pfiles = `sh -c "ls $lspatterns 2>/dev/null | sort -f"`
	if ( $#pfiles == 0 ) then
		echo "rmruns: no matching runs" >> /dev/stderr
		exit 1
	endif
	popd
	
	foreach file ( $pfiles )
		set run   = $file:e
		set files = \
			($files data/d.$run data/p.$run data/q.$run data/r.$run data/l.$run)
		set runs  = ($runs $run)
	end
endif

if( $force ) then
	echo rm -f $files
	rm -f $files
	exit 0
endif

if( $#runs == 0 ) then
	echo "rmruns: no matching runs" >> /dev/stderr
	exit 1
else
	if( $interactive ) then
		foreach run ( $runs )
			echo -n "remove run" $run"? (y[es]/no/a[bort]) "
			set ans = $<
			if( "$ans" == "y" || "$ans" == "yes" ) then
				set files = \
					(data/d.$run data/p.$run data/q.$run data/r.$run data/l.$run)
				#echo rm -f $files
				rm -f $files
			else if ( "$ans" == "a" || "$ans" == "abort" ) then
				echo aborted
				exit 0
			else
				echo "removing "$run" aborted"
			endif
		end
	else
		echo "Remove the following runs?"

		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 rnum = $#runs
		@   rows = $rnum / $cols

		@   rn   = $rows * $cols
		if( $rn < $rnum ) then
			@ rows = $rows + 1
		endif

		set row = 1
		set col = 0
		while( $row <= $rows )
			@ idx = $row + $rows * $col
			if( $idx <= $rnum ) then
				printf "%-${width}s" " $runs[$idx]"
			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

		echo -n "rmruns: (yes/no) "
		set ans = $<
		if( $ans == "yes" ) then
			#echo rm -f $files
			rm -f $files
		else
			echo "aborted"
		endif
	endif
endif
