#!/bin/tcsh

# experiment parameters
set ts          = 300		# length of timeseries
set stim        =   3		# number of input stimuli
set num_on      =  50		# time points per stimulus (between 0 and $ts/3)

# execution parameters
set iterations  = 100		# number of iterations
set seed        = 1234567	# initial random seed
set outdir      = stim_results
set LCfile      = $outdir/LC_sums

# ------------------------------------------------------------
# make sure $outdir exists

if ( ! -d $outdir ) then
    mkdir $outdir
    if ( $status ) then
	echo "failure, cannot create output directory, $outdir"
	exit
    endif
endif

# create empty LC file
echo -n "" > $LCfile

echo -n "iteration: 000"

# ------------------------------------------------------------
# run the test many times

foreach iter (`count -digits 3 1 $iterations`)

	# make some other random seed

	@ seed = $seed + 1

	# create random order stim files

	RSFgen -nt ${ts}        \
	    -num_stimts ${stim} \
	    -nreps 1 ${num_on}  \
	    -nreps 2 ${num_on}  \
	    -nreps 3 ${num_on}  \
	    -seed ${seed}       \
	    -prefix RSF.stim.${iter}. >& /dev/null

	# from the random order stim files, make ideal reference functions

	waver -GAM -dt 1.0 -input RSF.stim.${iter}.1.1D > wav.hrf.${iter}.1.1D
	waver -GAM -dt 1.0 -input RSF.stim.${iter}.2.1D > wav.hrf.${iter}.2.1D
	waver -GAM -dt 1.0 -input RSF.stim.${iter}.3.1D > wav.hrf.${iter}.3.1D

	# now evaluate the stimulus timings

	3dDeconvolve				\
	    -nodata				\
	    -nfirst 4				\
	    -nlast 299				\
	    -polort 1				\
	    -num_stimts ${stim}			\
	    -stim_file 1 "wav.hrf.${iter}.1.1D"	\
	    -stim_label 1 "stim_A"		\
	    -stim_file 2 "wav.hrf.${iter}.2.1D"	\
	    -stim_label 2 "stim_B"		\
	    -stim_file 3 "wav.hrf.${iter}.3.1D"	\
	    -stim_label 3 "stim_C"		\
	    -glt 1 contrasts/contrast_AB	\
	    -glt 1 contrasts/contrast_AC	\
	    -glt 1 contrasts/contrast_BC	\
		>& 3dD.nodata.${iter}

	# save the sum of the 3 LC values
	set nums = ( `awk -F= '/LC/ {print $2 * 10000}' 3dD.nodata.${iter}` )
	@ num_sum = $nums[1] + $nums[2] + $nums[3]

	echo -n "$num_sum = $nums[1] + $nums[2] + $nums[3] : " >> $LCfile
        echo    "iteration $iter, seed $seed"                  >> $LCfile

	mv RSF.stim.*.1D wav.hrf.*.1D 3dD.nodata* $outdir

	echo -n "\b\b\b$iter"
end

echo ""
echo "done, results are in '$outdir', LC sums are in '$LCfile'"
echo consider the command: "sort $LCfile | head -1"