#!/bin/csh -f

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

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

if ($#argv == 1) then
  set freqM = $1
else
  set freqM = ''
endif

if ( $?GDEVICE ) then
    # set the device ID of the 1st card to 'devid'.
    set devid = `echo $GDEVICE | sed 's/\([0-9]\).*$/\1/g'`
    set devs = ($GDEVICE)
else
    set devid = 0
    set ndev = `${rootpath}/hibutil/lsgrape | wc -l`  # num of dev + 1
    @ ndev--
    set devs = ()
    set i = 0
    while (${i} < ${ndev})
        set devs = (${devs} ${i})
        @ i++
    end
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${model}"

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

switch (${model})
  case 450:
  case 1800:
    set rev = 0
    breaksw

  case 460:
  case 2000:
#    set rev = 1
    breaksw

  case *:
    echo "No model number found in 'board_info' register of device ${devid}."
    echo "The board might be one of model450 or model1800."
    echo "Try 'config450' for the former, 'config1800' for the latter."
    exit 1
    breaksw
endsw

if (${freqM} == '') then
  switch (${model})
    case 460:
      set freqM = 33
      breaksw
    case 2000:
      set freqM = 34
      breaksw
    case *:
      set freqM = 32
      breaksw
  endsw
endif
echo freqM set to ${freqM}.

# now the following variables are set.
#   rev   : The iFPGA revision of the 1st device in use.
#   devs  : A list of device IDs of devices in use.

echo "Start configuration for ${#devs} device(s) (revision: ${rev}, device IDs: ${devs})..."
set i = 1
while (${i} <= ${#devs})
    (\
      setenv GDEVICE "$devs[$i]" ; \
      setenv GREVISION "${rev}" ; \
      ${rootpath}/gdr/test/configsub $devs[$i] ${freqM} ; \
    )
    sleep 1
    @ i++
end

onintr LABEL_HUP

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

exit 0

LABEL_HUP:
killall configsub pllconfig >& /dev/null
