#include <math.h>
#include <Keypad.h>
#include <LiquidCrystal.h>

const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', '+' },
  { '7', '8', '9', '-' },
  { '.', '0', '=', '*' }
};

uint8_t colPins[COLS] = { 2, A1, A2, A3 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 6, 5, 4, 3 }; // Pins connected to R1, R2, R3, R4

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal lcd(12, 11, 10, 9, 8, 7);

char key;
String buffer;
float numstore[20];
int actionstore[20];
int x = 0;

float calculations()
{
  float numout, numstor;
  numout = numstore[0];
  for(int i = 0; i < x; i++)
  {
    switch(actionstore[i]) {
    case 1:
      numstor = numout + numstore[i+1];
    break;
    case 2:
     numstor = numout - numstore[i+1];
    break;
    case 3:
      numstor = numout * numstore[i+1];
    break;
    }
    numout = numstor;
  }
  return numout;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  lcd.begin(16,2);
}

void loop() {
  // put your main code here, to run repeatedly: 
  key = keypad.getKey();
  if(key != NO_KEY)
  {
    if(key == 'A')
    {
      lcd.clear();
      buffer = "";
      for (int i = 0; i < x; i++)
      {
        numstore[i] = 0;
        actionstore[i] = 0;
      }
      x = 0;
    } else{
    lcd.print(key);
    Serial.println(key);
    if(isDigit(key) == true || key == '.')
    {
      buffer = buffer + key;
    }else if (key == '=')
    {
      numstore[x] = buffer.toFloat();
      buffer = "";
      x++;
      lcd.print(calculations());
    }
    else
    {
      numstore[x] = buffer.toFloat();
      if(key == '+')
      {
        actionstore[x] = 1;
      }
      else if(key == '-')
      {
        actionstore[x] = 2;
      }
      else if(key == '*')
      {
        actionstore[x] = 3;
      }
      buffer = "";
      x++;
    }
  }
  }
}