#!/bin/bash

# AlineTiming.bash v1
# Author: Shawn Alverson
# Created: 5/8/13
# Modified:
#  6 Nov 2014 S. Alverson
#    Added feedback ignore beam code modifiers
#    Cleaned/organized code
#  2 June 2014 J Nelson
#   change pm triggers from the top part matching bykik always and
#    the bottom part matching bykik when it's "off" TO
#    both top & bottom parts = exclude TS1-6 when it's off and both
#    parts match when it's on.
#  14 May 2014 J Nelson
#    exlcude mod 3 0x80 during force=no
#    LCLS user hutches will use this bit to say they Really want the beam.
#   3 May 2014 J Nelson
#    changed full rate no force to ts1only from ts1&4
#    see note below.
#  21 Nov 2013 Janice Nelson
#    Add a new mode: 60 Hz TS4
#    Too lazy to incorporate into existing logic - put it as a block 
#     before the old algorithm.
#  31 May 2013 Janice Nelson
#    Change lcbxkikchck1 to lcbxkik in the caputs in restore_def.
#  03 Jun 2013 Shawn Alverson
#    Add PM1 interlock reset at conclusion of script for 0 Hz readback glitch
#
# Description:
#  Script used by AlineTimingTable.edl to set timing masks for PM1 and BYKIK for Aline operation
#
# Syntax: AlineTiming.bash [OPTION] [rate] [mode] [force]
#         [rate]  => 0, 1, 5, 10, or 30 for requested ESA rate
#         [mode]  => 0: LCLS Full Rate
#                    1: Abort BYKIK every nth pulse
#                    2: True Burst Mode
#         [force] => 1: Force ESA rate to happen at requested rate regardless of LCLS running mode
#                    0: Do not force rate (ESA gets whatever beam is thrown away by LCLS)
#


# Define Constants
BYKIK="EVNT:SYS0:1:LCBYKIKCHCK1" # For A-Line kickers to fire, BYKIK must fire at same time
PM1A="EVNT:SYS0:1:LCALKIKCHCK1"  # A-Line kicker triggers
PM1B="EVNT:SYS0:1:LCALKIKCHCK"   # A-Line kicker triggers
BXKIK="EVNT:SYS0:1:LCBXKIKCHCK"  # Used for data aquisition triggers
MOD2_INC="I"                     # Pattern 2 Mod 2 Inclusion Mask PV
MOD2_EXC="N"                     # Pattern 2 Mod 2 Exclusion Mask PV
MOD3_INC="J"                     # Pattern 2 Mod 3 Inclusion Mask PV
MOD3_EXC="O"                     # Pattern 2 Mod 3 Exclusion Mask PV
MOD5_INC="L"                     # Pattern 2 Mod 5 Inclusion Mask PV

# Pockel Cell Permit
POCK=0x80000

# Rates
RATE_01HZ=0x800000
RATE_05HZ=0x400000
RATE_10HZ=0x200000
RATE_30HZ=0x100000
ONE_HERTZ=0x1000000
ONE_HERTZ_AND_POCK=0x80080
FIVE_HERTZ_AND_POCK=0x90000
TEN_HERTZ_AND_POCK=0x80400

# User Modes
FULL_RATE=0x36
TS1ONLY=0x3E
TS1ONLY_AND_BURST=0x7E
TS4ONLY=0x37
KICKER_LTU=0x20000000

# Force
PPICK=0x80

# Init Variables
useFiveHertz=1                  # NO!  normally use five_hertz # Normally use RATE_05HZ bit

Restore_Def() {
   # Restores beam back to default beam settings with beam only going to LCLS

   caput EVR:BSY0:MG01:EVENT14CTRL.OUT3 0           # Disable PM1 Ch.3 triggers

   caput EVNT:SYS0:1:LCBYKIKCHCK1.I 0x10000000      # BYKIK Inclusion Mask (MOD 2)
   caput EVNT:SYS0:1:LCBYKIKCHCK1.L 0x0             # BYKIK Inclusion Mask (MOD 5)
   caput EVNT:SYS0:1:LCBYKIKCHCK1.J 0x80000         # BYKIK Inclusion Mask (MOD 3)
   caput EVNT:SYS0:1:LCBYKIKCHCK1.N 0x36            # BYKIK Exclusion Mask (MOD 2, Timeslots)
   caput EVNT:SYS0:1:LCBYKIKCHCK1.O 0x00            # BYKIK Exclusion Mask (MOD 3)

   caput EVNT:SYS0:1:LCALKIKCHCK.I 0x0              # PM1 Inclusion Mask (MOD 2)
   caput EVNT:SYS0:1:LCALKIKCHCK.L 0x0              # PM1 Inclusion Mask (MOD 5)
   caput EVNT:SYS0:1:LCALKIKCHCK.J 0x0              # PM1 Inclusion Mask (MOD 3)
   caput EVNT:SYS0:1:LCALKIKCHCK.N 0x3F             # PM1 Exclusion Mask (MOD 2, Timeslots)
   caput EVNT:SYS0:1:LCALKIKCHCK.O 0x00             # BYKIK Exclusion Mask (MOD 3)

   caput EVNT:SYS0:1:LCALKIKCHCK1.I 0x0             # PM1 Inclusion Mask (MOD 2)
   caput EVNT:SYS0:1:LCALKIKCHCK1.L 0x0             # PM1 Inclusion Mask (MOD 5)
   caput EVNT:SYS0:1:LCALKIKCHCK1.J 0x0             # PM1 Inclusion Mask (MOD 3)
   caput EVNT:SYS0:1:LCALKIKCHCK1.N 0x3F            # PM1 Exclusion Mask (MOD 2, Timeslots)
   caput EVNT:SYS0:1:LCALKIKCHCK1.O 0x00            # BYKIK Exclusion Mask (MOD 3)

   caput EVNT:SYS0:1:LCBXKIKCHCK.I 0x0              # BXKIK Inclusion Mask (MOD 2)
   caput EVNT:SYS0:1:LCBXKIKCHCK.L 0x0              # BXKIK Inclusion Mask (MOD 5)
   caput EVNT:SYS0:1:LCBXKIKCHCK.J 0x0              # BXKIK Inclusion Mask (MOD 3)
   caput EVNT:SYS0:1:LCBXKIKCHCK.N 0x3F             # BXKIK Exclusion Mask (MOD 2, Timeslots)
   caput EVNT:SYS0:1:LCBXKIKCHCK.O 0x00             # BYKIK Exclusion Mask (MOD 3)

   caput IOC:IN20:EV01:RG01_I6_BYPS NOT_BYPASSED    # Feedback ignore for ESA 1Hz
   caput IOC:IN20:EV01:RG01_I7_BYPS NOT_BYPASSED    # Feedback ignore for ESA 5Hz
}

# Check Options
if [ $# -ne 0 ];then
   while getopts "hfd" Option
   do
      case $Option in
         h  )  echo -e "\nSyntax:  ./ESA_Rate.bash [OPTION] [rate] [mode] [force]"
               echo -e "Options: -h = Help\n         -d = Restore default configuration\n"
               exit 0;;
         f  )  useFiveHertz=1;;                 # Use FIVE_HERTZ bit rather than RATE_05HZ
         d  )  Restore_Def                      # If default option passed, restore machine to LCLS only state
               exit 0;;
      esac
   done
   shift $(($OPTIND-1))
fi

# Parse user inputs
case $# in
    0  )  echo "No rate selected, aborting..."
	  exit 1;;
    1  )  rate=$1
          mode=0
          force=0;;
    2  )  rate=$1
	  mode=$2
          force=0;;
    3  )  rate=$1
          mode=$2
          force=$3;;
    *  )  echo "Too many inputs given, check and try again..."
          exit 1;;
esac

#echo $rate $mode $force

#Sneak in settings for 60 Hz TS4 mode
if [ $mode -eq 3 ]; then
  timeslot=$TS4ONLY
  rateHex=0
  case $rate in
   0 ) Restore_Def
       exit 0;;
   1 ) abort=$ONE_HERTZ
       pockelperm=$POCK;;
   5 ) abort=0
       pockelperm=$FIVE_HERTZ_AND_POCK;;
  10 ) abort=0
       pockelperm=$TEN_HERTZ_AND_POCK;;
   * ) echo "I don't deal with rate != 1, 5, or 10"
       exit 1;;
  esac
else #not 60 Hz TS4 mode
    # If user requests FIVE_HERTZ modifier, this gets added onto pockelperm bit in MOD3 rather than MOD5
    if [ $useFiveHertz -eq 1 ];then
	case $rate in
	    0  )   Restore_Def  # No rate desired, restore default masks
		   exit 0;;
	    1  )   rateHex=0
	           pockelperm=$ONE_HERTZ_AND_POCK
	           caput IOC:IN20:EV01:RG01_I6_BYPS BYPASSED_ASSRT;;
	    5  )   rateHex=0
	           pockelperm=$FIVE_HERTZ_AND_POCK
	           caput IOC:IN20:EV01:RG01_I7_BYPS BYPASSED_ASSRT;;
	    10 )   rateHex=0
	           pockelperm=$TEN_HERTZ_AND_POCK;;
	    *  )   echo "Invalid rate selected! Check input and try again..."
                   exit 1;;
	esac
    else
	pockelperm=$POCK
	case $rate in
	    0  )  Restore_Def  # No rate desired, restore default masks
	          exit 0;;
	    1  )  rateHex=$RATE_01HZ;;
	    5  )  rateHex=$RATE_05HZ;;
	    10 )  rateHex=$RATE_10HZ;;
	    30 )  rateHex=$RATE_30HZ;;
	    *  )  echo "Invalid rate selected! Check input and try again..."
                  exit 1;;
	esac
    fi

    abort=0  # Initialize abort Mod 2 hex to 0

    if [ $force -eq 1 ];then
	timeslot=$TS1ONLY
	ppicker=0
    else 
	if [ $force -eq 2 ];then
	    ppicker=$PPICK
	else
	    ppicker=0
	fi

        # JNelson 3May2014
        # If lcls is full rate, then they aren't choosing pulses by abort every or burst
        #  so we have to use ts1only, otherwise we get double the rate requested.
	case $mode in
	    #0  )  timeslot=$FULL_RATE;;            # LCLS Full Rate OLD!!!
	    0  )  timeslot=$TS1ONLY;;              # LCLS Full Rate
	    1  )  timeslot=$FULL_RATE              # LCLS Abort every nth pulse
                  abort=$KICKER_LTU;;
	    2  )  timeslot=$TS1ONLY_AND_BURST;;    # LCLS Burst Mode
	    *  )  echo "Invalid LCLS mode selected! Check input and try again..."
	          exit 1;;
	esac
    fi
fi #close 60hzts4 mode chunk

 Set BYKIK, BXKIK, and PM1 timing masks
for i in $BYKIK $PM1A $PM1B $BXKIK; do
    caput $i.$MOD2_INC $abort
    caput $i.$MOD2_EXC $timeslot
    caput $i.$MOD3_INC $pockelperm
    caput $i.$MOD3_EXC $ppicker
    caput $i.$MOD5_INC $rateHex
done

caput KICK:BSY0:66:RESET 1   # Interlock reset on PM1 for 0 Hz glitch

# FOR TESTING
#for i in $BYKIK $PM1A $PM1B $BXKIK; do
#    echo $i.$MOD2_INC $abort
#    echo $i.$MOD2_EXC $timeslot
#    echo $i.$MOD3_INC $pockelperm
#    echo $i.$MOD3_EXC $ppicker
#    echo $i.$MOD5_INC $rateHex
#done

exit 0
