library(readxl)
library(dplyr)
library(tidyverse)
library(openxlsx)
setwd("C:/Users/Marcel/Desktop/Bachelor Thesis/Xsens Data/participant_37/Excel") # <- CHANGE FOR CORRECT PARTICIPANT!!!!!!!!!!!
col_types_vector <- rep("guess", 32)
col_types_vector[31] <- "numeric"
col_types_vector[32] <- "text"
# Create a vector to hold all data frames
list_of_data_frames <- list()

# Assuming the files for each BLock are named 'IDX_1.xlsx', 'IDX_2.xlsx', ..., 'IDX_10.xlsx'
for (i in 1:10) {
  file_name <- paste0("ID37_", i, ".xlsx") # <- UPDATE BASED ON ACTUAL PARTICIPANT!!!!!!!
  # Read each Excel file
  Xsensdf_block <- read_excel(file_name, col_types = col_types_vector)
  
  # Append to the list
  list_of_data_frames[[i]] <- Xsensdf_block
}

# Combine all data frames into one, and add a 'Block' column to each
Xsensdf <- bind_rows(list_of_data_frames, .id = "Block")

# Convert the 'Block' column to numeric
Xsensdf$Block <- as.numeric(Xsensdf$Block)

# Find indices where 'ns1:marker' equals 27
go_indices <- which(Xsensdf$`ns1:marker` == 27)

# Initialize the trial number and the block number
trial_number <- 0
block_number <- 1
Xsensdf$Trial <- NA
Xsensdf$Block <- NA

# Loop over the indices to assign the trial number and capture the 149 preceding rows + the GO signal row
for (go_index in go_indices) {
    start_index <- go_index - 149
    end_index <- go_index
  
    # Check if start index is within the valid range
    if (start_index > 0) {
        # Increment the trial number
        trial_number <- trial_number + 1
      
        # Assign the trial number
        Xsensdf$Trial[start_index:end_index] <- trial_number
      
        # Assign the block number based on the trial number
        Xsensdf$Block[start_index:end_index] <- ceiling(trial_number / 48)
    }
}

# Filter the dataset to only include rows that are part of a trial
Xsensdf_priortogo <- Xsensdf %>% filter(!is.na(Trial))

# Only include relevant collumns
Xsensdf_priortogo <- Xsensdf_priortogo %>% 
  select(`tc`,`Block`, `ns1:centerOfMass`, `ns1:marker`, Trial)

#Split ns1:centerOfMass into seperate collumns
Xsensdf_separated <- Xsensdf_priortogo %>%
  separate(`ns1:centerOfMass`, into = c("COM_displacement_X", "COM_displacement_Y", "COM_displacement_Z", 
                                        "COM_velocity_X", "COM_velocity_Y", "COM_velocity_Z",
                                        "COM_acceleration_X", "COM_acceleration_Y", "COM_acceleration_Z"),
           sep = " ", convert = TRUE)

# Add Subject Collumn
Xsensdf_separated <- Xsensdf_separated %>%
  mutate(Subject = 37) # <- CHANGE FOR CORRECT PARTICIPANT!!!!!!!!!!!!!!

# Creating a unique Index for each row (might be useful for Time Series)
Xsensdf_separated <- Xsensdf_separated %>%
  mutate(Index = row_number())

# Renumbering Trials within each Block, considering every 150 rows is one trial
Xsensdf_separated <- Xsensdf_separated %>%
  mutate(Trial = (Index - 1) %/% 150 + 1) %>%
  group_by(Block) %>%
  mutate(Trial = (Trial - 1) %% 48 + 1) %>%
  ungroup()

#Create "IndexWithinTrial", which numbers the rows belonging to each individual Trial from 1 to 150
Xsensdf_separated <- Xsensdf_separated %>%
  group_by(Block, Trial) %>%
  mutate(IndexWithinTrial = row_number()) %>%
  ungroup()

# Reordering the columns in the desired order
Xsensdf_separated <- Xsensdf_separated %>%
  select(Subject, Block, Trial, IndexWithinTrial, `tc`, `ns1:marker`,
         COM_displacement_X, COM_displacement_Y, COM_displacement_Z,
         COM_velocity_X, COM_velocity_Y, COM_velocity_Z,
         COM_acceleration_X, COM_acceleration_Y, COM_acceleration_Z,
         Index)
# Save the modified dataset to an Excel file
write.xlsx(Xsensdf_separated, "C:/Users/Marcel/Desktop/Bachelor Thesis/Xsens Data/Analysis/participant_37_priortogo.xlsx") # <- CHANGE FOR CORRECT PARTICIPANT!!!!!!!!!!!