# Joe's matlab code:
#function mag_ok = check_MADDNAME(bend_txt, btrim_txt)
#btrim_min = -1.1;
#btrim_max = -1;
#if abs(bend) < 1e-3 % bend is off
#    if (btrim < btrim_max) && (btrim > btrim_min)
#        mag_ok = 1; % OK
#    else
#        mag_ok = 0;
#    end
#else  % Bend is ON
#    if abs(btrim) < .02;
#        mag_ok = 1;
#    else
#        mag_ok = 0;
#    end
#end
#end
# =================================================

# First of all, is the BEND ON?  1 = YES, 0 = NO
record(calc, "$(BEND):ALMGNTON") {
  field(CALC, "(ABS(A)<B)?0:1")
  field(SCAN, "$(RATE) second")
  field(INPA, "$(BEND):BACT NPP NMS")
  field(INPB, ".001")
  field(FLNK, ALRM:SYS0:$(MADDNAME):MAGSINV)
}

# calculate whether the magnet is in error
# with respect to BEND on-ness and BTRM:BACT values
# if either magnet is INVALID, then this calc is set to
# 2 (invalid)

# first, is either magnet BACT invalid?
# this has to be a separate record to keep the
# calc expression in ALMGNTERRCALC short enough!
# 1 if yes, 0 if no
record(calc, "ALRM:SYS0:$(MADDNAME):MAGSINV") {
  field(CALC, "A>2||B>2?1:0")
  field(INPA, "$(BEND):BACT.SEVR")
  field(INPB, "$(BTRM):BACT.SEVR")
  field(FLNK, ALRM:SYS0:$(MADDNAME):ALMGNTERRCALC)
}
record(calc, "ALRM:SYS0:$(MADDNAME):ALMGNTERRCALC") {
  field(CALC, "F=1?2:A=1?(ABS(B)<E?0:1):(B>C&&B<D?0:1)")
  field(INPA, "$(BEND):ALMGNTON")
  field(INPB, "$(BTRM):BACT")
  field(INPC, "-1.1")
  field(INPD, "-1")
  field(INPE, ".02")
  field(INPF, "ALRM:SYS0:$(MADDNAME):MAGSINV")
  field(FLNK, ALRM:SYS0:$(MADDNAME):ALMGNTERR)
}

# put the result into a bi for names and alarm statuses
# 0 is good, 1 is bad, 2 is invalid
record(mbbi, "ALRM:SYS0:$(MADDNAME):ALMGNTERR") {
  field(DESC, "$(DESC)")
  field(INP, "ALRM:SYS0:$(MADDNAME):ALMGNTERRCALC.VAL")
  field(ZRSV, "NO_ALARM")
  field(ONSV, "MAJOR")
  field(TWSV, "INVALID")
  field(ZRST, "OK")
  field(ONST, "FAULT")
  field(TWST, "INVALID")
}

