#include <Keypad.h>
#include <LiquidCrystal_I2C.h>

#define MAX_WIDTH 20  // max amount of characters the screen can display

// display setup
LiquidCrystal_I2C lcd(0x27, 20, 4);
int cursorY = 0;
char characters[MAX_WIDTH];
int current_size = 0;

// keypad setup
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
uint8_t colPins[COLS] = {5, 4, 3, 2};
uint8_t rowPins[ROWS] = {9, 8, 7, 6};
char keys[ROWS][COLS] = {
    {'1', '2', '3', '+'},
    {'4', '5', '6', '-'},
    {'7', '8', '9', '*'},
    {'C', '0', 'E', '/'}  // E means enter
};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void processInput(char key) {
  if (current_size < MAX_WIDTH) { 
    characters[current_size] = key;
    current_size++;
    lcd.print(key);
  } else {
    error();
  }
}

void error(){ 
    lcd.clear();
    memset(characters, 0, sizeof(characters));
    current_size = 0;
}

int calculate(char *characters, int current_size) {
  for (int i = 0; i < current_size; i++){
    if (isdigit(characters[i])){
      
    }
    else{

  }
  }
}

void setup() {
  Serial.begin(9600);
  lcd.begin(20, 4);
  lcd.setCursor(0, 0);
}

void loop() {
  char key = keypad.getKey();

  if (key) {
    if (key == 'C') {
      error();
    }
    if (key == 'E') {
      calculate(characters, current_size);
    } 
    else if(key != 'C' && key != 'E') {
      processInput(key);
    }
  }
}