#!/bin/csh -f

cat << DESC_END
-----------------------------------------------------------------
 GRAPE-DR configuration program
   usage: config [devid] [freqM]
-----------------------------------------------------------------
DESC_END

set cmdname  = $0:t;
set rootpath = $0:h/../..
pushd $rootpath > /dev/null
set rootpath = `pwd`
popd > /dev/null

if ($#argv == 2) then
  set freqM = $2
  echo freqM set to ${freqM}.
else
  set freqM = 32
endif

set devid = 0
if ( $?GDEVICE ) then
    # set the device ID of the 1st card to 'devid'.
    set devid = `echo $GDEVICE | sed 's/\([0-9]\).*$/\1/g'`
endif

set model = `${rootpath}/hibutil/lsgrape -d ${devid} | \
             grep -v devid | sed 's/.*model\([0-9]\+\).*$/\1/g' | \
             sed 's/\s*\([0-9]\+\).*$/\1/' `

echo model${model}

switch (${model})
  case 450:
  case 460:
    echo configure model${model}
    ${rootpath}/gdr/test/configsub
    breaksw

  case 1800:
  case 2000:
    if ( $?GDEVICE ) then
        set cards = ($GDEVICE)
    else
        set cards = (0 1 2 3)
    endif

    echo configure model${model} chip\[${cards}\]

    set i = 1
    while (${i} <= ${#cards})
      (setenv GDEVICE "$cards[$i]" ; \
       ${rootpath}/gdr/test/configsub $cards[$i] ; \
       ${rootpath}/gdr/testv/pllconfig $cards[$i] ${freqM} )
      @ i++
    end # i
    breaksw

  case *:
    echo "No model number found in 'board_info' register of device ${devid}."
    echo "Try 'config450' for model450, 'config1800' for model1800 and model2000."
    exit 1
    breaksw

endsw

onintr LABEL_HUP

# wait until all sub programs are done.
set nruns = 1
while (${nruns} > 0)
  set nruns = `ps x | pgrep "configsub|pllconfig" | wc | awk '{print $1}'`
  sleep 1
end

exit 0

LABEL_HUP:
killall configsub pllconfig >& /dev/null
