--------------------------------------------------- 
-- FBA Tutorials
--
-- Tutorial / 22 / Calculator
--
--------------------------------------------------- 
--
-- Simple calculator to demonstrate user input
-- Developed using FBA The Creator 0.2.0.91.
-- Jeremy Eble (eblejr@phrebh.com, http://www.phrebh.com)
--
-- This is released without guarantee or warranty.  Every care has been taken to ensure
-- stability and accuracy; use at your own risk.
--
--------------------------------------------------- 

include("initialization.fba")

-- Call custom function to initialize calculator variables.
initializeCalc()

-- Draw numbers to the screen.
function drawValue()
  Readout=""..Readout
  intROlen=string.len(Readout)
  -- Limit the screen to ten characters, including decimal point and negative sign.
  if intROlen>10 then 
    intROlen=10
    Readout=string.sub(Readout,1,10) 
  end
  intSOS=0
  for i=1, intROlen do
    intSOS=intSOS + arrSpace[string.byte(Readout,i)] + fontSpacing
  end
  -- Right-justify the value on the screen.
  drawgfxtext(fontNumbers, 226 - intSOS, 18, Readout, 0, 0, 0) 
end


function onmainloop()	
  drawimage(imgBackground, 0, 0)
  if pushed >= 0 then 
    drawimage(imgPushed, tblButtons[pushed]['bounds']['x1'], tblButtons[pushed]['bounds']['y1'])
  end
  for i=0, 24 do
    x=tblButtons[i]['faceplacement']['x1']
    y=tblButtons[i]['faceplacement']['y1']
    if pushed==i then
      x=x+1
      y=y+1
    end
    drawimage(imgFaces,x,y,tblButtons[i]['face']['x1'],tblButtons[i]['face']['y1'],tblButtons[i]['face']['x2'] + faceOffset,tblButtons[i]['face']['y2'] + faceOffset)
  end
  drawValue()
  if memory~=0 then drawimage(imgM, 12, 12) end
end


function onstylusup(x,y)
  if (y>=65 and y<=103) then row=1 
  elseif (y>=110 and y<=148) then row=2
  elseif (y>=155 and y<=193) then row=3
  elseif (y>=200 and y<=238) then row=4
  elseif (y>=245 and y<=283) then row=5
  else row=0 end
  if (x>=11 and x<=49) then col=1 
  elseif (x>=56 and x<=94) then col=2
  elseif (x>=101 and x<=139) then col=3
  elseif (x>=146 and x<=184) then col=4
  elseif (x>=191 and x<=229) then col=5
  else col=0 end
  if (row~=0 and col~=0) then 
    if pushed==arrRC[row][col] then
      doCalc[pushed]()
    end
  end
  pushed=-1
end


function onstylusdown(x,y)
  if (y>=65 and y<=103) then row=1 
  elseif (y>=110 and y<=148) then row=2
  elseif (y>=155 and y<=193) then row=3
  elseif (y>=200 and y<=238) then row=4
  elseif (y>=245 and y<=283) then row=5
  else row=0 end
  if (x>=11 and x<=49) then col=1 
  elseif (x>=56 and x<=94) then col=2
  elseif (x>=101 and x<=139) then col=3
  elseif (x>=146 and x<=184) then col=4
  elseif (x>=191 and x<=229) then col=5
  else col=0 end
  if (row~=0 and col~=0) then pushed=arrRC[row][col] end
end
