--regulate in between these in normal operation
NORMAL_THRESHOLD_U = 8000000
NORMAL_THRESHOLD_L = 7000000
--control rod pos for normal operation
NORMAL_ROD_POS = 81

--proportionally increase production when energy
--storage drops below this level
--(by removing control rods)
HIGH_THRESHOLD = 6000000


local active = false
local ctrl_rods = NORMAL_ROD_POS

local reactor = peripheral.wrap("back")
local mon = peripheral.wrap("right")

print("Monitoring reactor...")

while (true)
do
    --setup monitor
    mon.clear()

    --get reactor energy
    local energy = reactor.getEnergyStored()
    --display
    mon.setCursorPos(1, 1) --why is there no print() ???
    mon.write(energy)
    mon.write("RF")

        
    if (energy > NORMAL_THRESHOLD_U)
    then
        active = false
    else
        if (energy < NORMAL_THRESHOLD_L)
        then
            active = true
            if (energy < HIGH_THRESHOLD)
            then
                --proportional control
                ctrl_rods = NORMAL_ROD_POS * (energy / HIGH_THRESHOLD)
            end
        end
    end
    
    --actually set state
    mon.setCursorPos(1, 2)
    if (active) 
    then
        reactor.setActive(true)
        mon.write("On")
    else
        reactor.setActive(false)
        mon.write("Off")
    end
    
    mon.setCursorPos(1, 4)
    reactor.setAllControlRodLevels(ctrl_rods)
    mon.write(ctrl_rods)
    mon.write("%")


    --display power produced
    mon.setCursorPos(1, 3)
    mon.write(math.floor(reactor.getEnergyProducedLastTick()))
    mon.write("RF/t")
    

    --also check if fuel has run out
    --(if the fuel inside the reactor isn't
    --getting refilled anymore)
    
    local deltaFuel = reactor.getFuelAmountMax() - reactor.getFuelAmount()
    if (deltaFuel > 1000) --more than 1 bucket
    then
        mon.setCursorPos(1, 5)
        mon.write("REFUEL!")
    end
                        
    sleep(1)
end