ComputerCraft Archive

Tollway by CreeperGoBoom

computer monitor unknown forum

Description

Tollway by CreeperGoBoom

Installation

Copy one of these commands into your ComputerCraft terminal:

Pastebin:pastebin get QEai09dx tollway_by_creepergoboom
wget:wget https://pastebin.com/raw/QEai09dx tollway_by_creepergoboom
Archive:wget https://cc.shobie.xyz/cc/get/pb-QEai09dx tollway_by_creepergoboom
Quick Install: wget https://cc.shobie.xyz/cc/get/pb-QEai09dx Tollway by CreeperGoBoom

Usage

Run the program after downloading

Tags

monitorforumprograms

Source

View Original Source

Code Preview

--Tollway by CreeperGoBoom
--Fixed large tolls not working
--
---------CREDITS---------
--Lupus590: Up and coming hungry toll idea and programming issues.
--Programming issues:
--Leo - Discord
--Ocawesome101 - Discord
--dael - discord
--SquidDev - Discord
--Fatbuychummy - Discord

--Gollark - Helping fix autoupdater

local tArgs = {...}
local autoUpdate=true    --toggles auto updating function

--Program vars. Do not change these
local config = {} --stores all vars entered by player + some defaults
config.version = "2.3 STABLE"
config.conSize = 27
config.statusScreenUsesTitle = false
config.statusScreenShowsDebt = false
-- config.redIn="bottom"
-- config.redOut="bottom"
-- config.redPass="bottom"
-- config.bundledInColor=colors.white
-- config.bundledOutColor=colors.white
-- config.bundledPassColor=colors.white

if tArgs[1] == "getVersion" then
  return config.version
end
local list = {}
local results = {}
local topay
local count = 0
local rs = redstone
local statusScreen
local open = false
local errorNoteBlock
local hungryCheck

local requiredAPIFuncs = {
  "loadConfig",
  "colorPrint",
  "getUserInput",
  "getAnswer",
  "getAnswerWithPrompts",
  "findPeripheral",
  "peripheralCheck",
  }

local function httpGet(stringURL, stringFileNameToSaveTo)
  local h, err = http.get(stringURL)
  if not h then printError(err) return nil end
  local f = fs.open(stringFileNameToSaveTo, "w")
  f.write(h.readAll())
  f.close()
  h.close()
  return true
end

if not fs.exists("apis/CGBCoreLib.lua") then
  if not httpGet("https://pastebin.com/raw/xuMVS2GP", "apis/CGBCoreLib.lua") then
    error("Error: Dependancy 'CGBCoreLib' could not be downloaded. Please connect your internet and restart")
  end
end

local core = require("apis/CGBCoreLib") --Contains complete function library used accross multiple programs and to minimize code size.

for _ , func in pairs(requiredAPIFuncs) do --For API checking to ensure not outdated
  if not core[func] then
    if not httpGet("https://pastebin.com/raw/xuMVS2GP", "apis/CGBCoreLib.lua") then
      error("Error: Your version of CGBCoreLib is outdated! Please connect your internet and restart!")
    else
      os.reboot()
    end
  end
end

local function rsControlMsg()
  if config.redOutputType == "redstone" then
    print("Admission query input side: ", config.redIn)
    print("Player pass input side: ", config.redPass)
    print("Redstone control output side: ", config.redOut)
  elseif config.redOutputType == "bundled" then
    print("Bundled In/Out side: ", config.bundledSide)
    print("Admission query color: ", config.bundledInColor)
    print("Player pass color: ", config.bundledPassColor)
    print("Tollway control color: ", config.bundledOutColor)
  end
end

local function updateConfigFile()
  config.usesErrorNoteBlock=nil
  config.usesStatusScreen=nil
  config.errorNoteBlockIsNetworked=nil
  config.statusScreenIsNetworked=nil
  config.test=nil
  config.pushDir = nil
  if config.chestSide and config.version ~="2.2 STABLE" and not config.destination then 
    repeat
      print("Patcher question:")
      config.destination = core.getUserInput("What is the network name of the destination chest?")
      local chest2 = peripheral.wrap(config.destination)
    until chest2 
  end
  local success, sData = pcall(function() return textutils.serialize(config) end) 
  if not success then 
    error("Oops! serialization failed. Config contains a non serializable function")
  elseif success then
    local file = fs.open("config", "w")
    file.write(sData)
    file.close()
  end
end
  

local pcSides = rs.getSides()

local function startupConfig()
  local answer
  local chest
  local chest2
  if not fs.exists("config") then
    term.clear()
    term.setCursorPos(1, 1)
    print("Tollway by CreeperGoBoom")
    print("Version: ", config.version)
    print("Easy Setup Config Wizard")    --This is where all the prints for the easy setup wizard need to be
    print("Toll behaviour:")
    config.tollType = core.getAnswer("What type of toll do you want: freepass, perma-toll or debt-toll?", {"freepass", "debt-toll", "perma-toll"})
    if config.tollType == "debt-toll" then
      config.tollDebt = tonumber(core.getUserInput("How much do you want to charge in total before this tollway is set to freepass?"))
      config.tollDebtRemaining = config.tollDebt
    end
    if config.tollType ~= "freepass" then
      print("Container info:")
      --local answer = core.getAnswer("Is your chest networked? y or n? (networked meaning cabled up)", {"y", "n"})
      repeat
        answer=core.peripheralCheck("minecraft:chest",core.getAnswerWithPrompts("I didnt find the chest networked or present, what side is it on if it is connected?",{"left","right","front","back","top","bottom","network"}))
        chest = peripheral.wrap(answer)
        if not chest then answer = core.getUserInput("OK. What is the full name of your networked chest?")
          chest = peripheral.wrap(answer)
          if not chest then
            print("Oops! Nothing there yet, please place a chest or check direction and try again.")
          end
        end
      until chest.size()
      config.conSize = chest.size()
      print("Chest or inventory size detected: "..chest.size().." slots!")
      config.chestSide=answer
      repeat
        config.destination = core.getUserInput("What is the network name of the destination chest or inventory?")
        chest2 = peripheral.wrap(config.destination)
      until chest2
      hungryCheck = core.getAnswer("Would you like to set your toll to: 'PAYP' (Pay As You Pass) or 'hungry' mode (will eat until paid and player passes)?", {"PAYP", "hungry"})
      if hungryCheck == "PAYP" then
        config.isHungry = false
        config.tollMax = config.conSize * 64
      else
        config.isHungry = true
      end
      print("Payment Info:")
      answer = core.getAnswer("Would you now like to set up your toll payment type using your chest? (Optional: Allows for checking exact item info. This is also useful for password type where you only wish to use a specific item)", {"y", "n"})
      if answer == "y" then
        local id, cName
        repeat
          print("Please deposit your desired payment type into slot 1 of your container and press enter. You can use custom named items.(This does not record qty)")
          io.read()
          if chest.getItemMeta(1) then
            id = chest.getItemMeta(1).name
            cName = chest.getItemMeta(1).displayName
          else
            print("No item found to record as payment type. Please ensure the item is in slot 1 and try again.")
          end
          print("Item Details found:")
          print("ID: ", id)
          print("Display Name: ", cName)
          local answer2 = core.getAnswer("Is this what you want to use? y or n?", {"y", "n"})
        until answer2 == "y"
        config.payType = cName
        config.payTypeID = id
      elseif answer == "n" then
        print("Security Notice: Item ID check: DISABLED")
        config.payType = core.getUserInput("What is the Display Name of the item you would like to use?")
      end
      config.toll = core.getUserInput("How many " .. config.payType .. " would you like to charge per admission?")
      config.tollMax = config.toll*64
      if tonumber(config.toll) > config.tollMax and config.isHungry == false then
        repeat
          print("Container size verification error. Toll amount more than container size!")
          print("You selected (you/container): ", config.toll, "/", config.tollMax)
          print("Note: This error does not occur while hungry toll mode is on")
          config.toll = core.getUserInput("How many " .. config.payType .. " would you like to charge per admission?")
        until config.toll < config.tollMax
      end
      config.toll = tonumber(config.toll)
    end --This is where redstone control questions come in
    --config.redOutputType = core.getAnswerWithPrompts("What control type are you using?",{"redstone", "bundled","plethora-manipulator", "plethora-redstone-integrator"})
    config.redOutputType = core.getAnswerWithPrompts("What control type are you using?",{"redstone", "bundled"})
    if config.redOutputType == "redstone" then
      print("Redstone dust control:")
      config.redIn = core.getAnswer("What side will input for admission query?", {"front", "back", "left", "right", "top", "bottom"})
      config.redPass = core.getAnswer("What side will input for player pass?", {"front", "back", "left", "right", "top", "bottom"})
      config.redOut = core.getAnswer("What side will output for tollway control?", {"front", "back", "left", "right", "top", "bottom"})
    elseif config.redOutputType == "bundled" then
      print("Bundled cable control:")
      config.bundledSide = core.getAnswer("What side is your cable attached?", {"front", "back", "left", "right", "top", "bottom"})
      config.bundledInColor = colors[core.getAnswer("what color will input for player query?", {"white", "orange", "magenta", "lightBlue", "yellow", "lime", "pink", "gray", "lightGray", "cyan", "purple", "blue", "brown", "green", "red", "black"})]
      config.bundledPassColor = colors[core.getAnswer("what color will input for player pass?", {"white", "orange", "magenta", "lightBlue", "yellow", "lime", "pink", "gray", "lightGray", "cyan", "purple", "blue", "brown", "green", "red", "black"})]
      config.bundledOutColor = colors[core.getAnswer("what color will output for tollway control?", {"white", "orange", "magenta", "lightBlue", "yellow", "lime", "pink", "gray", "lightGray", "cyan", "purple", "blue", "brown", "green", "red", "black"})]
    --[[elseif config.redOutputType == "plethora-redstone-integrator" then
      print("Plethora Redstone Integrator Control.")
      repeat
        config.rsIntegrator=core.getAnswerWithPrompts("redstone_integrator",core.getAnswerWithPrompts("I didnt find the integrator networked or present, what side is it on if it is connected?",{"left","right","front","back","top","bottom","retry"}))
      until config.redOutputType ~= "retry"
      print("Redstone Integrator: FOUND.")
      print("Configuration:")
      config.rsIntegratorIn=core.getAnswerWithPrompts("What side will Input to the integrator?",{"east","west","north","south","up","down"})]]
    end
    print("Optional Features")
    if config.tollType == "freepass" then
      print("Note block: N/A")
    end
    answer = core.getAnswer("Would you like to set up a Status screen? y or n? Make sure monitor is networked or next to tollway for faster config", {"y", "n"})
    if answer == "y" then
      config.usesStatusScreen = true
      if peripheral.find("monitor") then
        config.statusScreenName = "monitor"
        statusScreen = peripheral.find(config.statusScreenName)
        statusScreen.setTextScale(0.5)
        statusScreen.clear()
        statusScreen.setCursorPos(1, 2)
        statusScreen.write("Configuration")
        statusScreen.setCursorPos(1, 3)
        statusScreen.write("In Progress!")
        answer = core.getAnswer("I have found your monitor and printed 'Configuration In Progress'. Is this showing on your monitor? y or n", {"y", "n"})
        if answer == "n" then
          answer = core.getAnswer("OK, is your monitor networked? y or n?", {"y", "n"})
          if answer == "y" then
            repeat
              print("What is the full name of your monitor? ie: monitor_0?")
              config.statusScreenName = io.read()
              if not peripheral.wrap(config.statusScreenName) then
                print("Error: monitor not found. please try again")
              end
            until peripheral.wrap(config.statusScreenName)
          else
            repeat
              answer = core.getAnswer("What side is your monitor?", {"front", "back", "left", "right", "top", "bottom"})
              config.statusScreenName = answer
              if not peripheral.wrap(config.statusScreenName) then
                print("Error: monitor not found. please try again")
              end
            until peripheral.wrap(config.statusScreenName)
          end
        end
      else
        answer = core.getAnswer("Is your monitor networked? y or n?", {"y", "n"})
        if answer == "y" then
          repeat
            print("What is the full name of your monitor? ie: monitor_0?")
            config.statusScreenName = io.read()
            if not peripheral.wrap(config.statusScreenName) then
              print("Error: monitor not found. please try again")
            end
          until peripheral.wrap(config.statusScreenName)
        else
          repeat
            answer = core.getAnswer("What side is your monitor?", {"front", "back", "left", "right", "top", "bottom"})
            config.statusScreenName = answer
            if not peripheral.wrap(config.statusScreenName) then
              print("Error: monitor not found. please try again")
            end
          until peripheral.wrap(config.statusScreenName)
        end
      end
      answer = core.getAnswer("would you like to set a Title to your status screen, Eg. 'Welcoem to disneyland!' y or n", {"y", "n"})
      if answer == "y" then
        config.statusScreenUsesTitle = true
        config.statusScreenTitle = core.getUserInput("What will be the title? Please ensure it is sorrect before pressing enter")
        print("You entered: '", config.statusScreenTitle, "'. Press enter to continue")
        io.read()
      end
      if config.tollType == "debt-toll" then
        answer = core.getAnswer("You selected debt-toll. Would you like your status screen to show debt info? 'Amount left before free'", {"y", "n"})
        if answer == "y" then
           config.statusScreenShowsDebt = true
        end
      end
    end 
    
    if config.tollType ~= "freepass" then
      answer = core.getAnswer("Would you like to set up a note block to sound for Insufficent funds? Make sure it is networked or next to tollway for faster config", {"y", "n"})
      if answer == "y" then
        repeat
          answer = core.peripheralCheck("minecraft:noteblock",core.getAnswerWithPrompts("I didnt find the note block networked or present, what side is it on if it is connected?",{"left","right","front","back","top","bottom","network","retry"}))
          errorNoteBlock=peripheral.wrap(answer)
          if not errorNoteBlock then answer = core.getUserInput("OK. What is the full name of your noteblock?")
            config.errorNoteBlock=answer
            errorNoteBlock=peripheral.wrap(answer)
            if not errorNoteBlock then
              print("I didn't find your noteblock. please check the name and try again")
            end
          end
        until peripheral.wrap(answer)
        print("Note Block: FOUND")
        repeat
          config.errorSoundCount = core.getUserInput("How many times do you want your noteblock to sound?")
          if not tonumber(config.errorSoundCount) then
            print("Thats not a number, please try again")
          end
        until tonumber(config.errorSoundCount)
        config.errorSoundCount = tonumber(config.errorSoundCount)
        repeat
          config.errorSoundDelay = core.getUserInput("What delay would you like to set? (above 0.175)")
          if not tonumber(config.errorSoundDelay) then
            print("Thats not a number, please try again")
          elseif tonumber(config.errorSoundDelay) < 0.175 then
            print("I cannot allow below 0.175, else the note block may sound too fast or only sound once. you are welcome to change this in config after ESCW is finished though to experiment... var is errorSoundDelay")
          end
        until tonumber(config.errorSoundDelay) and tonumber(config.errorSoundDelay) >= 0.175
        config.errorSoundDelay = tonumber(config.errorSoundDelay)
      end
    end
          
    repeat
      term.clear()
      term.setCursorPos(1, 1)
      print("Tollway by CreeperGoBoom. version: ", config.version)
      print("Settings Confirmation Page")
      print("Toll Type: ", config.tollType)
      print("Toll Control type: ", config.redOutputType)
      if config.tollType == "freepass" then
        print("Chest: NOT NEEDED")
        rsControlMsg() --displays redstone control prints
      end
      --if tollType=="freepass" then
        
      --elseif tollType=="debt-toll" then
      
      --elseif tollType=="perma-toll" then
      
      --end
      local cDone = core.getUserInput("Please confirm your settings. Enter Y to save, Enter N to start over. Note: Non case sensitive.")
      if cDone == "y" then
        term.clear()
        term.setCursorPos(1, 5)
        print("Thankyou for using the Easy Setup Config Wizard. Have a nice day!")
        print("To reconfigure. Delete 'config' and restart.")
        print("Now starting...")
        sleep(5)
      elseif cDone == "n" then
        startupConfig()
      else
        print("I only understand Y or N (non case sensitive). Please try again.")
      end
      cDone = cDone:lower()
    until cDone == "y"
    updateConfigFile()
  else
    config = core.loadConfig("config")
  end
end

function orderConfig()
  config[1].version=config.version
  config[2].toll=config.toll
  updateConfigFile()
end

function AutoUpdate()
  if autoUpdate then
    local result
    local h, err = http.get("https://pastebin.com/raw/QEai09dx")
    if not h then printError(err) return end
    local f = fs.open("startup", "w")
    f.write(h.readAll())
    f.close()
    h.close()
    local get = loadfile("startup")
    result = get("getVersion")
    if result~=config.version then
      config.version=result
      updateConfigFile("config")
      os.reboot()
    end
  end
end

local function RingBell(count, delay)
  if config.errorNoteBlock then
    for _ = 1, count do
      errorNoteBlock.playNote(4,2,5)
      sleep(delay)
    end
    return true
  end
end

local function TollwayControl() --opens tollway if closed. also returns if it was successful.
  print("getting event")
  os.pullEvent("redstone")
  if not open and config.redOutputType == "redstone" and rs.getInput(config.redIn, true) then
    print("Now Opening")
    open = true
    rs.setOutput(config.redOut, true)
    return open
  elseif not open and config.redOutputType == "bundled" and colours.test(rs.getBundledInput(config.bundledSide), config.bundledInColor) then
    print("Now Opening")
    open = true
    rs.setBundledOutput(config.bundledSide, config.bundledOutColor)
    print("Opening")
    return open
  elseif open and config.redOutputType == "redstone" and rs.getInput(config.redPass, true) then
    print("Now Closing")
    open = false
    rs.setOutput(config.redOut, false)
    return open
  elseif open and config.redOutputType == "bundled" and colours.test(rs.getBundledInput(config.bundledSide), config.bundledPassColor) then
    print("Now Closing")
    open = false
    rs.setBundledOutput(config.bundledSide, 0)
    print("Closing")
    return open
  end
end


local colorNames = {}
for k, v in pairs(colors) do
  colorNames[v] = k
end

local function StatusScreenUpdate(stringLine1, stringLine2)
  if config.statusScreenName then
    statusScreen.setTextScale(0.5)
    statusScreen.clear()
    if config.statusScreenUsesTitle then
      statusScreen.setCursorPos(1, 1)
      statusScreen.write(config.statusScreenTitle)
    end
    statusScreen.setCursorPos(1, 2)
    statusScreen.write(stringLine1)
    statusScreen.setCursorPos(1, 3)
    statusScreen.write(stringLine2)
    if config.isHungry then
      statusScreen.setCursorPos(1, 4)
      statusScreen.write("Hungry Mode: " .. tostring(config.isHungry))
    end
    if config.statusScreenShowsDebt and config.tollType == "debt-toll" then
      statusScreen.setCursorPos(1, 5)
      statusScreen.write("Remaining until free: " .. config.tollDebtRemaining .. " x " .. config.payType)
    end
  end
end

startupConfig()
AutoUpdate()
--orderConfig()

--Code--
term.clear()
term.setCursorPos(1, 1)
print("Tollway by CreeperGoBoom")
print("Version: ", config.version)
print("Current Config Screen")
print("Toll Type: ", config.tollType)
print("Redstone control type: ", config.redOutputType)
if config.redOutputType == "redstone" then
  print("Player admit query side: " .. config.redIn)
  print("Redstone out control side: " .. config.redOut)
  print("Admit fulfill detection side: ", config.redPass)
else
  rs.setBundledOutput(config.bundledSide, 0)
  print("Bundled control side: ", config.bundledSide)
  print("Player query input color: ", colorNames[config.bundledInColor])
  print("Player pass input color: ", colorNames[config.bundledPassColor])
  print("Tollway control output color: ", colorNames[config.bundledOutColor])
end
if config.statusScreenName then
  print("Status Screen: Yes")
else
  print("Status Screen: No")
end
if not (config.tollType == "freepass") then
  if config.errorNoteBlock then
    print("Insufficient funds noteblock: Yes")
  else
    print("Insufficient funds noteblock: No")
  end
  if not config.isHungry then
    print("Hungry: No")
    print("Maximum payment selectable: ", config.tollMax, " ", config.payType)
  else
    print("Hungry: Yes")
  end
  print("Payment Selected: ", config.payType, " x ", config.toll, ".")
end

function updateDebt(amount)
  if config.tollType == "debt-toll" then
    config.tollDebtRemaining = config.tollDebtRemaining - amount
    if config.tollDebtRemaining <= 0 then config.tollType = "freepass" end
    updateConfigFile()
  end
end

--wraps peripherals if they are used in config, else they are not used. Allows for aesthetic tollway design.
statusScreen = core.findPeripheral("monitor",config.statusScreenName)
errorNoteBlock = core.findPeripheral("note_block",config.errorNoteBlock)
chest = core.findPeripheral("chest",config.chestSide)
if config.destination then chest2 = peripheral.wrap(config.destination) end

topay=config.toll

function condenseItems()
  for i = 1,config.conSize do
    chest.pushItems("self",i,64)
  end
  return
end

function getChestInfo()
  for slot = 1, config.conSize do
    if config.payTypeID and output[slot] and output[slot].displayName == config.payType and output[slot].name == config.payTypeID then
      results[slot] = output[slot].count
    elseif meta and meta.displayName==config.payType then
      results[slot] = output[slot].count
    else
      sleep()
    end
  end
end

local funcs = {}
local output = {}
local sz
if not config.chestSide then
sz = 1
else
sz = chest.size()
end
local slotsPerFunc = math.ceil(sz / 12) -- lets start with 8 functions



for i = 1, sz, slotsPerFunc do
  local function tmp()
    for o = i, i + slotsPerFunc do
      if o > sz then return end
      output[o] = chest.getItemMeta(o)
    end
  end
  table.insert(funcs, tmp)
end

while true do
sleep()
  while config.tollType ~= "freepass" and config.isHungry and (open or not open) do
    local remaining = config.toll
    while remaining > 0 and not open do
    --while not open do
      --local event = os.pullEvent()
      --condenseItems()
      parallel.waitForAll(table.unpack(funcs))
      for slot = 1, config.conSize do
        if config.payTypeID and output[slot] and output[slot].displayName == config.payType and output[slot].name == config.payTypeID then
          results[slot] = output[slot].count
        elseif meta and meta.displayName==config.payType then
          results[slot] = output[slot].count
        else
          sleep()
        end
      end
      print("Using hungry mode")
      StatusScreenUpdate("Status: Processing payment", "Cost: " .. config.toll .. " x " .. config.payType)
      for key,_ in pairs(results) do
        if key == nil then
          sleep()
        end
        if remaining == 0 then 
          --print(remaining)
          break
        elseif chest.pushItems(config.destination,key,config.toll)==config.toll then
          updateDebt(config.toll)
          remaining = 0
          --print(remaining)
        elseif remaining < config.toll then if chest.pushItems(config.destination,key,remaining)==remaining then
          updateDebt(remaining)
          remaining = 0
          --print(remaining)
          end
        elseif chest.pushItems(config.destination,key,1)==1 then
          updateDebt(1)
          remaining = remaining - 1
          --print(remaining)
        else
          sleep()
        end
      end
    end
    while remaining == 0 and not open do 
      StatusScreenUpdate("Status: Paid", "Please proceed")
      TollwayControl()
    end
    --end    
    --while open do
    
    --os.pullEvent("redstone") --there is some redstone event
    while remaining == 0 and open do if open and TollwayControl() then remaining=config.toll end
    --os.pullEvent("redstone") 
    --if open then TollwayControl() end
    end
  end
  while config.tollType ~= "freepass" and topay > 0 and config.isHungry==false do
  sleep()
    StatusScreenUpdate("Status: Awaiting Payment.", "Cost: " .. config.toll .. " x " .. config.payType)
    if config.redOutputType == "redstone" then
      rs.setOutput(config.redOut, false)
    elseif config.redOutputType == "bundled" then
      rs.setBundledOutput(config.bundledSide, 0)
    end
    os.pullEvent("redstone")
    if config.redOutputType == "redstone" and
    rs.getInput(config.redIn) 
    or config.redOutputType == "bundled" 
    and colours.test(rs.getBundledInput(config.bundledSide), config.bundledInColor) then
      --sleep(0.25)
      print("player query detected")
      condenseItems()
      parallel.waitForAll(table.unpack(funcs))
      for slot = 1, config.conSize do
        if config.payTypeID and output[slot] and output[slot].displayName == config.payType and output[slot].name == config.payTypeID then
          results[slot] = output[slot].count
        elseif meta and meta.displayName==config.payType then
          results[slot] = output[slot].count
        else
          sleep()
        end
      end
      for key, val in pairs(results) do
        print(results[key])
        print(key, " : ", val)
        count = count + val
      end
      if count >= config.toll then
        print("Total payment detected: ", count)
        print("Amount to pay: ", topay)
        --RingBell(1, 0)
        repeat
          --print(i," : ",v)
          --sleep(0)
          for key, val in pairs(results) do
            if val >= topay then--This is where the tollway / item push code should go
              print("Granting access: Code 1")
              updateDebt(config.toll)
              StatusScreenUpdate("Status: Paid", "Please proceed")
              if config.redOutputType == "redstone" then
                rs.setOutput(config.redOut, true)
                open = true
              elseif config.redOutputType == "bundled" then
                rs.setBundledOutput(config.bundledSide, config.bundledOutColor)
                open = true
              end
              print("This should only be printing once")
              if chest.pushItems(config.destination, key, config.toll) then
              --if chest.drop(key, config.toll, config.pushDir) then
                topay = 0
                open = true
                break
              else
                print("toll not payable from current slot, moving on")
              end
            elseif val < topay or val >= topay then
              print("Counting pennies")
              StatusScreenUpdate("Status: Processing payment", "Cost: " .. config.toll .. " x " .. config.payType)
              if  val < topay  then
                chest.pushItems(config.destination, key, val) 
                topay = topay - val
                updateDebt(val)
                print("Amount left to pay: ", topay)
                if topay < 0 then
                  error("Oops! something went wrong and chest was overcharged!")
                end
              elseif val >= topay then
                chest.pushItems(config.destination, key, topay)
                updateDebt(topay)
                topay = 0
                print("Payment success!")
              end
            end
          end
        until topay == 0
        -- print("This should only be printing once")
        -- if config.tollType=="debt-toll" then
          -- config.tollDebtRemaining=config.tollDebtRemaining-config.toll
          -- if config.tollDebtRemaining <= 0 then
            -- config.tollType="freepass"
          -- end
          -- updateConfigFile()
        -- end
      else
        StatusScreenUpdate("Status: Access Denied!", "Insufficient Funds")
        print("Access denied! Insufficient funds!")
        RingBell(config.errorSoundCount, config.errorSoundDelay)
        sleep(1)
      end
      if config.redOutputType == "redstone" then
        rs.setOutput(config.redOut, true)
      elseif config.redOutputType == "bundled" then
        rs.setBundledOutput(config.bundledSide, config.bundledOutColor)
      end
      --reset everything
      results = {}
      count = 0
    end
  end
  while topay == 0 and config.tollType ~= "freepass" and config.isHungry==false do
    --os.pullEvent("redstone")
    if TollwayControl() then
      topay = config.toll
      open = false
      StatusScreenUpdate("Status: Awaiting Payment.", "Cost: " .. config.toll .. " x " .. config.payType)
    end
    sleep()
  end
  while config.tollType == "freepass" do
    StatusScreenUpdate("Status: OK.", "Cost: Free.")
    --os.pullEvent("redstone") --there is some redstone event
    TollwayControl()
  end
end

-- while ispaid do
  -- print("access granted")
  -- ispaid=false
-- end