function bin(dec)
        local result = ""
       
        repeat
                local divres = dec / 2
                local int, frac = math.modf(divres)
                dec = int
                result = math.ceil(frac) .. result
        until dec == 0
       
        return result
end

function hex(dec)
        local result = ""
        local base16 = {"A","B","C","D","E","F"}
       
        repeat
                local remainder = dec % 16
                if remainder >= 10 then
                        remainder = base16[remainder - 9]
                end
                result = remainder .. result
               
                dec = math.modf(dec / 16)
        until dec == 0
       
        return result
end

-- logic for recieving chat and sending to router.
local delay = 0.06
local compID = 1 -- to be fetched from file later
local globalID = 18
local compID_bin = bin(compID)
local msgList = {}
local sending = false
local busy = false

local recList = {1,16,256,4096}
local rec = recList[compID]
local trg = rec * 2

local sList = {4,64,1024,16384}
local sRec = sList[compID]
local sTrg = sRec * 2

local speaker = peripheral.wrap("bottom")

term.clear()

function printDict(data)
  for i, v in pairs(data) do
    write(tostring(i).." - "..tostring(v) .. " ")
  end
  print()
end

function setHeader(type)
  sending = true  
  if type == "chat" then
    header = "C"
  elseif type == "cmd" then
    header = "D"
  end
  --print("\nHeader:" .. header)
 
  local rStr = ""
  local rList = {}
  local hList = strSplit(header)
    
  for i,v in ipairs(hList) do 
    rStr = rStr .. getBitStr(hList[i])
  end
  
  rStr = padValue(rStr, 8)
  rList = strSplit(rStr)
  sendBits(rList)  
  --print()
end

function setSender(sender)
	sender = padValue(bin(sender),8)
	sendBits(strSplit(sender))
end

function setDest(dest)
	dest = padValue(bin(dest),8)
	sendBits(strSplit(dest))
end

function sendBits(bList)
  for i,v in ipairs(bList) do
    sendBit(v)
    --write(v)
    sleep(delay)
  end
end

function setFooter()
  for i= 1,8 do sendBit("0") --write(0)
  sleep(delay) end
end

function setColor(side, color, val)
  local sOutput = rs.getBundledOutput(side)
  local output = colors.combine(sOutput,color)
  if val == true then
    rs.setBundledOutput(side, output)
  elseif val == false then
    rs.setBundledOutput(side,colors.subtract(output,color))
  end  
end

function sendBit(val)  
  if val == "1" then
    --speaker.playNote(0,8)
    setColor("back", sRec,true)
    setColor("back", sTrg,true)
    sleep(delay)
    setColor("back", sTrg,false)
    setColor("back", sRec,false)   
  elseif val == "0" then
    --speaker.playNote(0,16)
    setColor("back", sTrg, true)
    sleep(delay)
    setColor("back", sTrg, false)
  end  
end

function colorTest(color)
  if colors.test (redstone.getBundledInput("back"), color) then
    return true
  else
    return false
  end
end

function getInput()
  if colorTest(rec) then
    return true
  else
    return false
  end
end

function modulo(a,b)  
  return a - math.floor(a/b)*b
end

function binToDec(num)
	local bStr = ""
    while num > 0 do    
		local rem = modulo(num, 2)
		bStr = rem .. bStr
		num = (num-rem)/2
    --print("CurLimit: " .. bVal)
	end
	return bStr
end

function getBitStr(c)

  local bVal = string.byte(c)
  --print("String Byte Value: " .. bVal)
  
  local bStr = ""
  while bVal > 0 do    
    local rem = modulo(bVal, 2)
    bStr = rem .. bStr
    bVal = (bVal-rem)/2
    --print("CurLimit: " .. bVal)
  end
  return padValue(bStr, 8)   
  
end

function padValue(str, len)
  local rS = ""
  if string.len(str) < len then
    rS = string.rep("0", len - string.len(str))
    rS = rS .. str
  else
    rS = str
  end  
  return rS
end

function strSplit(text)
  local rList = {}
  for i = 1, string.len(text) do
   table.insert(rList,string.sub(text, i ,i) )    
  end
  return rList
end

function sendStr(inVar)
  local rStr = ""
  local rList = {}
  local sList = strSplit(inVar)
  --printDict(sList)  
  for i, n in ipairs(sList) do
    rStr = rStr .. getBitStr(sList[i])
  end
  
  rList = strSplit(rStr)
  local x = os.clock()  
  for i, n in ipairs(rList) do
    sendBit(n)
    --write(n)
    sleep(delay)  
  end
  
  sending = false
  --print(n)
  --print("Time elapsed: ", os.clock() - x, " seconds" )    
end

function recieveMsg()

end

function sendMsg(header)
  printChat()

  local w, h = term.getSize()
  --term.setCursorPos(1,1)
  term.setCursorPos(1 + 6,h)
  msg = read()
  term.clearLine()
  write("Dest:")
  dest = read()
  term.clearLine()
  
  setHeader(header)
  setSender(globalID)
  setDest(dest)
  sendStr(msg)
  setFooter()
end


function getBit(cL, c)
  local ret = 0
  if colors.test(cL, c) then
    ret = 1
  end
  --speaker.playNote(0,20)
  return ret
end

function lightLamp(side)
  redstone.setOutput(side,true)
  sleep(0.05)
  redstone.setOutput(side,false)
end

function writeBit(cL,c)
  local ret = 0
  if colors.test(cL, c) then
    ret = 1
  end
  write(ret)
  return ret
end

function getMsg() 
    local bitCount = 0
    local cByte = 0
    local msg = ""
    local header = ""
	local sender = ""
    local ident = ""
    local gX = 1
    local gY = 2
    
    --term.redirect(peripheral.wrap("right"))
    --local monitor = peripheral.wrap("left")
    --monitor.setTextScale(1)
    
    local trans = {}
    trans["C"] = "<Chat"
    
  while os.pullEvent("redstone") do
   input = rs.getBundledInput("back")
   if colors.test(input, trg) then
    busy = true
    local input2 = rs.getBundledInput("back")
    iV = writeBit(input2, rec)
    cByte = bit.bor(cByte, bit.blshift(iV, 7 - bitCount))
    bitCount = bitCount + 1
    if bitCount == 8 then
      if cByte == 0 then
	  
	  function msgWrite()
		    msg = ( trans[header]  .. "[" .. ident .. "]: " .. msg or "UNKNOWN(".. header  .. "[" .. ident .. "]: " .. msg )
	  end
	  
	    if pcall(msgWrite) then
			--success
		else
			msg = "NIL"
		end
		table.insert(msgList, msg)
		busy = false
		printChat()
		--monitor.write(str)
        header = ""
		sender = ""
        ident = ""
        msg = ""
       elseif header:len() < 1 then
         header = header..string.char(cByte)
       elseif ident:len() < 1 then
         ident = ident .. cByte
	   elseif sender:len() < 1 then
         sender = sender.. cByte
       else
        msg = msg .. string.char(cByte)
      end
      bitCount = 0
      cByte = 0
     end
  end
 end
 --return true
end

function printC(sText) 
	local w, h = term.getSize() 
	local x, y = term.getCursorPos() 
	x = math.max(math.floor((w / 2) - (#sText / 2)), 0) 
	term.setCursorPos(x, y) 
	print(sText) 
end 

function printChat()
	term.clear()
	term.setCursorPos(1,1)
	local w, h = term.getSize()
	str_div = string.rep("-", w - string.len("-"))
	print(str_div)
	printC("|Profan's Chat Module|")
	write("		CID: " .. compID .. " GID: " .. globalID)
	print(str_div)
	
	for i=0,5 do
		if msgList[i] ~= "" then
			print(msgList[i])
		end
	end
	
	term.setCursorPos(1,h)
	print(str_div)
	write("Input: ")
	
end

function runChat()   
  while true do 
  local floor     
    parallel.waitForAny (
    --sendMsg("chat",read("*")), getMsg()
      function()
        floor = sendMsg("chat")
      end,
      function()
        floor = getMsg()
        sleep(0.001)  
      end    
    )
    --sendMsg("chat",read("*"))   
  end
end

runChat()
