library(tidyverse)
library(zoo)

# Set 
flow_threshold = 10
flow_n = 10
n_smooth = 256/2
window_secs = 3
gap_window_secs = 0.1
vol_jump_threshold = 100
viz_time_start = 0
viz_time_end = 1500

dir <- "C:/Users/spd001/johan_fluxmed/1.33i signals/"

files <- list.files(dir)

check_leads <- function(data, n_lead, threshold){
  
  out <- rep(0,length(data))
  
  for(i in 1:length(data)){
    if(all(abs(data[i:min(i+n_lead,length(data))]) > threshold)){
      out[i] <- sign(data[i])
    } 
  }
  
  return(out)
}

undo_jumps <- function(data, threshold){
  
  for(i in 1:(length(data)-1)){
    jump_size = data[i+1] - data[i]
    if(abs(jump_size) > threshold){
      data[(i+1):length(data)] <- data[(i+1):length(data)] - jump_size
    } 
  }
  
  return(data)
}

for(i in files){
  
  fn = paste0(dir,i)
  
  data = read.delim(fn,skip = 5)[-1,] %>%
    filter(!is.na(Time)) %>%
    mutate(across(everything(),function(x) as.numeric(gsub(",",".",x))),
           File = as.numeric(str_split(i," ")[[1]][1])) %>%
    select(File,Time,Volume,Flow,Paw,CO2)
  
  
  mod <- lm(Volume ~ Time, data=data)
  
  data$Volume_detrend <- data$Volume - predict(mod,data)
  
  if(i == first(files)){
    out_data = data
  } else{
    out_data = rbind(out_data,data)
  }

  print(i)

}

out_data <- out_data %>%
  group_by(File) %>%
  mutate(Flow_ma =as.numeric(rollapply(Flow,
                                       n_smooth,
                                       mean,
                                       align='right',
                                       fill=0)),
         direction = check_leads(Flow_ma,
                                 n_lead = flow_n,
                                 threshold = flow_threshold),
         Volume = undo_jumps(Volume,vol_jump_threshold),
         in_start = direction > 0 & direction > lag(direction),
         in_start_lead = lead(in_start,n_smooth,default=F),
         breath_n = cumsum(in_start_lead),
  ) %>%
  filter(breath_n > 2,breath_n < max(breath_n)-2)

measures <- out_data %>%
  group_by(File,breath_n) %>%
  arrange(Time) %>%
  summarize(Duration = last(Time[direction==1]) - first(Time[direction==1]),
            Time = min(head(Time,256*window_secs)),
            Flow = max(head(Flow,256*window_secs)),
            Paw = max(head(Paw,256*window_secs)),
            Volume = max(head(Volume,256*window_secs)) - first(Volume),
            CO2 = max(CO2)) %>%
  mutate(breath_n = ifelse(Time - lag(Time) > gap_window_secs | is.na(lag(Time)),breath_n,breath_n-1)) %>%
  group_by(File,breath_n) %>%
  summarize(across(everything(),max))


out_data %>%
  mutate(Volume = Volume_detrend) %>% 
  select(-in_start,-in_start_lead,-Volume_detrend) %>%
  filter(Time > viz_time_start, Time < viz_time_end) %>%
  pivot_longer(-Time) %>%
  ggplot(aes(x = Time,
             y=value)) +
  geom_line() +
  geom_point(data = pivot_longer(filter(measures,Time > viz_time_start, Time < viz_time_end),-c(Time,breath_n,File)),
             color = "red") +
  facet_grid(name~File,scales = "free_y")

measures %>%
filter(Time > viz_time_start, Time < viz_time_end) %>%
pivot_longer(-c(Time,breath_n,File)) %>%
  ggplot(aes(x = Time,
             y=value)) +
  geom_line() +
  facet_grid(name~File,scales = "free_y")


ggsave(paste0("C:/Users/spd001/johan_fluxmed/out/measures2.png"))

#Assume leak is constant and correct linear trend



write_excel_csv2(measures,file = "C:/Users/spd001/johan_fluxmed/out/measures2.csv")
write_excel_csv2(out_data,file = "C:/Users/spd001/johan_fluxmed/out/data2.csv")