namespace eval lambdawatch {} {
}

proc stdConfig::lambdawatch {safefield maxfield safetemp args} {
  controller syncedprot
  prop write lambdawatch::write

  pollperiod 15 15

  obj LambdaWatch rd
  prop read lambdawatch::loop
  prop cntlim 10
  prop cnt 0

  kids "lambda watch" {
    node safefield out
    default $safefield
    node maxfield out
    default $maxfield
    node safetemp out
    default $safetemp
    node coiltemp -text par "$args"
    prop width 32
  }
}

proc lambdawatch::write {} {
  hupdate [sct parent]/status ""
  sct update [sct target]
  return idle
}

proc lambdawatch::loop {} {
  set saff [hval [sct]/safefield]
  set mf [result mf]
  if {$mf <= $saff} {
    if {[hval [sct]/status] ne "" && ([result mf limit] > $saff || [result mf] < $saff - 0.01)} {
      hupdate [sct]/status ""
    }
    sct update 4.5
    return idle
  }
  set saft [hval [sct]/safetemp]
  set maxf [hval [sct]/maxfield]
  set limt [expr $saft + ($maxf - $mf) / ($maxf - $saff) * (4.5 - $saft)]
  sct update $limt
  set cnt [sct cnt]
  foreach node [hval [sct]/coiltemp] {
    if {[hval $node] > $limt} {
      clientput [format "WARNING: %s > %g" $node $limt]
      incr cnt 2
    } else {
      incr cnt -1
    }
  }
  if {$cnt < [sct cntlim]} {
    sct cnt [expr max(0, $cnt)]
    return idle
  }
  if {[result mf targetValue] > $saff || ![string match "* mf *" " [split [listexe]] "]} {
    set txt [format "lambda controller getting warm, set mf and limit to %s" $saff]
    hupdate [sct]/status $txt
    run mf $saff
    mf limit $saff
    clientlog "ERROR: $txt"
  }
  return idle
}
