#include <EEPROM.h>

#define EEPROM_START_ADDR 0
#define NUM_ROOMS 4  // Update to support 4 rooms

// Function to update the transition matrix with recent data
void updateTransitionMatrix(float transitionMatrix[][NUM_ROOMS], int recentMovements[], int numDataPoints) {
  for (int i = 0; i < numDataPoints - 1; i++) {
    int currentRoom = recentMovements[i] / 10;  // Extract the tens digit as current room
    int nextRoom = recentMovements[i] % 10;     // Extract the ones digit as the next room

    // Increment the transition count from the current room to the next room
    transitionMatrix[currentRoom - 1][nextRoom - 1]++;
  }

  // Calculate probabilities (normalize the counts to probabilities)
  for (int i = 0; i < NUM_ROOMS; i++) {
    int totalCount = 0;
    for (int j = 0; j < NUM_ROOMS; j++) {
      totalCount += transitionMatrix[i][j];
    }
    for (int j = 0; j < NUM_ROOMS; j++) {
      if (totalCount > 0) {
        transitionMatrix[i][j] /= totalCount;
      } else {
        transitionMatrix[i][j] = 0.0;
      }
    }
  }
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  const int numDataPoints = 20;
  int recentMovements[] = {41, 32, 21, 13, 32, 21, 12, 23, 31, 13, 32, 21, 12, 23, 32, 31, 12, 23, 44};

  // Initialize the transition matrix with zeros
  float transitionMatrix[NUM_ROOMS][NUM_ROOMS] = {{0.0}};

  // Update the transition matrix with the recent data
  updateTransitionMatrix(transitionMatrix, recentMovements, numDataPoints);

  // Display the transition matrix in a styled table format on the Serial Monitor
  Serial.println("Transition Matrix:");
  Serial.println("=================");
  Serial.print("From \\ To | ");
  for (int i = 1; i <= NUM_ROOMS; i++) {
    Serial.print("Room ");
    Serial.print(i);
    Serial.print(" | ");
  }
  Serial.println();

  Serial.println("-----------------------------------");

  for (int i = 0; i < NUM_ROOMS; i++) {
    Serial.print("Room ");
    Serial.print(i + 1);
    Serial.print("   | ");
    for (int j = 0; j < NUM_ROOMS; j++) {
      Serial.print(transitionMatrix[i][j], 2);  // Display probabilities with 2 decimal places
      Serial.print("  | ");
    }
    Serial.println();
  }
  Serial.println("=================");

  // Your prediction code goes here...

  // Wait for some time before updating the transition matrix again
  delay(5000);
}