# Define the Polybius matrix

# Create a 4x10 matrix to be used for decryption.
polybius <- matrix(c(" ", "Z", "M", "D", " ", "K", "W", "Q", " ", "G", 
                     "V", " ", "A", " ", "R", " ", "E", " ", "T", "O", 
                     " ", "J", "I", "S", "B", "P", "Y", " ", "F", " ", 
                     "L", " ", " ", "C", " ", "U", "H", "N", " ", "X"), 
                   nrow = 4, byrow = TRUE)

# Give labels to the rows and columns for easier reference.
rownames(polybius) <- 0:3
colnames(polybius) <- 0:9

# Show the Polybius matrix.
polybius

# Start of Decryption Task

# Step 1: Define the ciphertext to be decrypted

# Ciphertext contains the numbers that represent characters in the Polybius matrix.
cipher_numbers <- c("24160", "63616", "14162", "61935", "14163", "71602", "26222", "33719", "18008")

# Step 2: Combine the ciphertext into one sequence

# Combine all parts of the ciphertext into one long string.
combined_cipher <- paste(cipher_numbers, collapse = "")

# Step 3: Decrypt the ciphertext

# Create an empty list to keep the decrypted letters.
decrypted_message <- c()

# Go through each pair of numbers in the combined string.
for (i in seq(1, nchar(combined_cipher), by = 2)) {
  # Get the row and column numbers from the string.
  row <- as.integer(substr(combined_cipher, i, i))
  col <- as.integer(substr(combined_cipher, i + 1, i + 1))
  
  # Check if the row and column are valid.
  if (!is.na(row) && !is.na(col) && row >= 0 && row <= 3 && col >= 0 && col <= 9) {
    # Get the character from the matrix and add it to the message.
    character <- polybius[row + 1, col + 1]
    decrypted_message <- c(decrypted_message, character)
  } else {
    # If the row or column is invalid, add "!" to the message.
    decrypted_message <- c(decrypted_message, "!")
  }
}

# Step 4: Combine decrypted letters into a single message

# Combine all the letters to form the final decrypted message.
plaintext <- paste(decrypted_message, collapse = "")

# Step 5: Show the decrypted message

# Print the final message.
plaintext


### Encryption Task

# Step 1: Encrypt a message using a keyword "APPLE"

# Message to encrypt and the keyword used.
message_to_encrypt <- c("R", "A", "I", "S", "E", "T", "H", "E", "F", "L", "A", "G")
encrypt_keyword <- c("A", "P", "P", "L", "E")

# Step 2: Get the coordinates for each letter in the message and keyword.
find_coords <- function(letter) {
  for (i in 1:4) {
    for (j in 1:10) {
      if (polybius[i, j] == letter) {
        return(c(i - 1, j - 1))  # Convert to 0-based indexing
      }
    }
  }
  return(NA)  # If the letter isn't found, return NA
}

# Get coordinates for the message letters.
message_coords <- lapply(message_to_encrypt, find_coords)
# Get coordinates for the keyword letters, repeating it to match the message length.
keyword_coords <- lapply(rep(encrypt_keyword, length.out = length(message_to_encrypt)), find_coords)

# Step 3: Encrypt the message
encrypted_result <- c()
for (i in 1:length(message_to_encrypt)) {
  msg_coord <- message_coords[[i]]
  key_coord <- keyword_coords[[i]]
  
  # Add the message coordinates and keyword coordinates together.
  new_row <- (msg_coord[1] + key_coord[1]) %% 4
  new_col <- (msg_coord[2] + key_coord[2]) %% 10
  
  # Create the encrypted code and add it to the result.
  new_code <- paste0(new_row, new_col)
  encrypted_result <- c(encrypted_result, new_code)
}

# Step 4: Combine the encrypted codes into one string and group them by 5 characters.
combined_encrypted <- paste(encrypted_result, collapse = "")
finaltext <- c()
for (j in seq(1, nchar(combined_encrypted), by = 5)) {
  part <- substr(combined_encrypted, j, j + 4)
  finaltext <- c(finaltext, part)
}

# Step 5: Show the final encrypted message
finaltext

# Decryption Task Using Keyword

# Step 1: Input Ciphertext and Keyword
cipher_data <- "48521 82559 53320 83151 44382 13349 40352 42260 48521 84349 48343 23518"
key_word <- "LEMON"  # The keyword for decryption

# Step 2: Clean Ciphertext and Split into Pairs
# Remove spaces and split into pairs
cipher_no_space <- gsub(" ", "", cipher_data)  # Remove spaces
cipher_pairs <- numeric()  # Initialize empty numeric vector for pairs

index <- 1
while (index < nchar(cipher_no_space)) {  # Loop through characters in steps of 2
  pair <- substr(cipher_no_space, index, index + 1)  # Extract 2-digit pair
  cipher_pairs <- c(cipher_pairs, as.numeric(pair))  # Convert and store in the vector
  index <- index + 2  # Increment by 2
}

# Step 3: Convert Keyword to Numeric Values
key_vals <- c()  # Initialize vector for keyword numeric values
for (char in strsplit(key_word, "")[[1]]) {  # Split keyword into characters
  for (r in 0:3) {  # Loop through rows
    for (c in 0:9) {  # Loop through columns
      if (polybius[r + 1, c + 1] == char) {  # Match character in Polybius square
        key_vals <- c(key_vals, r * 10 + c)  # Store numeric equivalent
      }
    }
  }
}

# Step 4: Decrypt Ciphertext
decrypted_text <- ""  # Initialize empty string for the decrypted message
key_length <- length(key_vals)  # Length of the numeric keyword sequence

for (i in seq_along(cipher_pairs)) {  # Loop through all ciphertext pairs
  cipher_val <- cipher_pairs[i]  # Current ciphertext pair
  key_val <- key_vals[(i - 1) %% key_length + 1]  # Cycle through keyword values
  
  # Adjust cipher value by subtracting the keyword numeric value
  adjusted_val <- cipher_val - key_val
  if (adjusted_val < 0) {  # Wrap negative values
    adjusted_val <- adjusted_val + 40
  }
  
  # Extract row and column from the adjusted value
  row_num <- adjusted_val %/% 10  # Integer division gives the row
  col_num <- adjusted_val %% 10   # Modulo gives the column
  
  # Fetch the corresponding letter from the Polybius matrix
  letter <- polybius[row_num + 1, col_num + 1]
  if (letter != " ") {  # Ignore spaces
    decrypted_text <- paste0(decrypted_text, letter)  # Append letter to the decrypted message
  }
}

# Step 5: Display Decrypted Message
decrypted_text  # Final output: "THEWISEWARRIORAVOIDSTHEBATTLEJ"