#!/bin/bash
#Arguments to this script: $1=req_rate $2=req_charge
#To clear any preloaded instruction not pushed to the firmware
set -x

caput TPG:SYS0:1:DST00:CNSL 1
caput TPG:SYS0:1:DST00:CNSL 0

#Store in variables: Charge, Rate, allowed_pc, pc1_maxQ, pc2_maxQ, rate_name

charge=`caget -t TPG:SYS0:1:DST00:CHARGE_REQ`
echo "the charge is $charge"
r=`caget -t TPG:SYS0:1:DST00:RATE_SEL`
stringarray=( $r )
rate=${stringarray[0]}
k=${stringarray[1]}
c0=$rate
if [ "$k" == "kHz" ];then 
  K=1000
  rate=$(( $rate * $K ))
  c1="_kHz_"
  else c1="_Hz_"
  fi
echo "the rate is $rate"
c2="_pC"
rate_name=`echo "$c0$c1$charge$c2"`
#request=$(($charge * $rate)) 
echo $rate_name
request=`echo $charge*$rate | bc -l`
echo "the requested power is $request"
pc1_maxQ=300 #pC
pc2_maxQ=300000 #pC #EIC variation from 300000 pC
 
#Verification: Is the requested charge allowed?
mps_pc=`caget -t TPG:SYS0:1:ALW00:MPSLATCH`
echo "The TPG is latched on PC $mps_pc from MPS"

#Checking if we are in PC =0 then do not allow any rate
if [ "$mps_pc" == 0 ];then
  echo "Running in power class 0"
#    echo "MPS doesn't allow ANY rate-charge combination, please try again after MPS recovers to PC>1!"
#    caput TPG:SYS0:1:DST00:CHARGE_RATE_STAT 2
#    alw=0 #Not allowed by MPS
#    exit 0
fi

#Checking if we are in PC =1 then do not allow any rate
if [ "$mps_pc" == 1 ];then
    echo "Running in power class 1"
    if [ $request -gt $pc1_maxQ ];then
        echo "MPS doesn't allow this rate-charge combination, please try again!"
        caput TPG:SYS0:1:DST00:CHARGE_RATE_STAT 2
        alw=0 #Not allowed by MPS
	exit 0
        else alw=1 #Allowed by MPS
    fi
fi

#Checking if we are in PC =2 then schedule the rates if the power is less than 300.000pC
if [ "$mps_pc" == 2 ];then
    echo "Running in power class 2"
    if [ $request -gt $pc2_maxQ ];then
        echo "MPS doesn't allow this rate-charge combination, please try again!"
        caput TPG:SYS0:1:DST00:CHARGE_RATE_STAT 2
        alw=0 #Not allowed by MPS
	exit 0 
        else alw=1 #Allowed by MPS
    fi
fi
#When a combination of Charge-Rate is allowed, the sequence engine gets programmed with the requested combination.
##
#For testing
##
alw=1

if [ "$alw" == 1 ];then #If allowed by MPS
        caput TPG:SYS0:1:DST00:CHARGE_RATE_STAT 1
        #Clear all the preprogrammed sequence engines not in use
        in_use=`caget -t TPG:SYS0:1:DST00:RUNIDX`
        echo The sequence in use is: $in_use
        COUNTER=0
        while [  $COUNTER -lt 64 ]; do
          IDX="IDX"
          if [ $COUNTER -lt 10 ]
            then INDEX_IN_USE="TPG:SYS0:1:DST00:SEQ0$COUNTER$IDX"
          fi
          if [ $COUNTER -gt 9 ]
            then INDEX_IN_USE="TPG:SYS0:1:DST00:SEQ$COUNTER$IDX"
          fi
          rate_index=`caget -t $INDEX_IN_USE`
	  if [ $rate_index -gt 0 ];then
            echo "rate index in use = $in_use"
            echo "rate_index= $rate_index"
            # To verify if not configured: if [ -z "$rate_index" ]
            if [ "$rate_index" != $in_use ];then
              echo Clear preprogrammed sequence engine not in use
              caput TPG:SYS0:1:DST00:RMVIDX $rate_index
              caput TPG:SYS0:1:DST00:RMVSEQ 1
              caput TPG:SYS0:1:DST00:RMVSEQ 0
            fi
          fi
         echo Done with Seq Eng: $COUNTER Index: $rate_index
	 let COUNTER=COUNTER+1
        done
        #Program a new sequence engine:
        caput TPG:SYS0:1:DST00:INS 0
        caput TPG:SYS0:1:DST00:DESCINSTRS $rate_name
        #Instructions to configure the timing pattern
        #Check which marker rappresents the requested rate
        if [ $rate -eq 1 ]
           then marker=6
        fi
        if [ $rate -eq 10 ]
           then marker=5
        fi
        if [ $rate -eq 100 ]
           then marker=4
        fi
        if [ $rate -eq 1000 ]
           then marker=3
        fi
        if [ $rate -eq 10000 ]
           then marker=2
        fi
        #Special case where we need to use marker 0 and branch every 10
        if [ $rate -eq 100000 ]
           then marker=8
        fi
        if [ $rate -eq 910000 ]
           then marker=0
        fi
        instr_cnt=0
        if [ "$marker" == 8 ];then
          #Sub-sequence program for 100KHz
          #Specify the rate to 1MHz marker 0 and branch every 10
          #1) Fixed Rate Sync to 1Hz
          caput -a TPG:SYS0:1:DST00:INSTR 3 0 6 1
          instr_cnt=$(( $instr_cnt + 1 ))
          #2) Assign the charge and request the beam
          caput -a TPG:SYS0:1:DST00:INSTR 2 4 $charge
          instr_cnt=$(( $instr_cnt + 1 ))
          #3) Branch every 10 
          caput -a TPG:SYS0:1:DST00:INSTR 3 0 0 10
          instr_cnt=$(( $instr_cnt + 1 ))
          #4) Branch instruction back to a specific instruction
          caput -a TPG:SYS0:1:DST00:INSTR 2 2 1
          instr_cnt=$(( $instr_cnt + 1 ))
        else
          #1) Fixed Rate Sync to 1Hz
          caput -a TPG:SYS0:1:DST00:INSTR 3 0 6 1
          instr_cnt=$(( $instr_cnt + 1 ))
          #2) Fixed Rate Sync to requested rate
          caput -a TPG:SYS0:1:DST00:INSTR 3 0 $marker 1
          instr_cnt=$(( $instr_cnt + 1 ))
          #3) Assign the charge and request the beam
          caput -a TPG:SYS0:1:DST00:INSTR 2 4 $charge
          instr_cnt=$(( $instr_cnt + 1 ))
          #4) Branch instruction back to a specific instruction
          caput -a TPG:SYS0:1:DST00:INSTR 2 2 1
          instr_cnt=$(( $instr_cnt + 1 ))
        fi
        sleep 0.1s
        #Check if the instr_cnt = number of instructions programmed
        instr_cnt_RBV=`caget -t TPG:SYS0:1:DST00:INSTRCNT`
        if [ "$instr_cnt" -eq "$instr_cnt_RBV" ];then
            #Insert new sub-sequence instructions
            caput TPG:SYS0:1:DST00:INS 1
            caput TPG:SYS0:1:DST00:INS 0
            #Find the inserted sub-sequence index
            COUNTER=0
            while [  $COUNTER -lt 64 ]; do
              IDX="IDX"
	      DESC="DESC"
              if [ $COUNTER -lt 10 ]
                then prefix="TPG:SYS0:1:DST00:SEQ0$COUNTER"
              fi
              if [ $COUNTER -gt 9 ]
                then prefix="TPG:SYS0:1:DST00:SEQ$COUNTER"
              fi
	      desc_name="$prefix$DESC"
              name=`caget -t $desc_name`
              #stringarray=($name_caget)
              #name= ${stringarray[1]}
              # To verify if not configured: if [ -z "$name" ]
              if [ "$name" == "$rate_name" ];then
                idx_to_run=`caget -t $prefix$IDX`
                caput TPG:SYS0:1:DST00:RUNIDX $idx_to_run
                COUNTER=64
              fi
	      let COUNTER=COUNTER+1
            done
        fi
            #Schedule/Force New Sequence Engine
            caput TPG:SYS0:1:DST00:DEST 0
            caput TPG:SYS0:1:DST00:JUMPADDR 0
            caput TPG:SYS0:1:DST00:FORCERESET 1
            caput TPG:SYS0:1:DST00:FORCERESET 0
    
fi
