#
# Author: Andrew Mehnert, Centre for Ophthalmology & Visual Science, UWA
#
# SYNOPSIS: Processes one or more "..kymo_direction_histograms.csv" files
#           produced by "compute_kymograph_direction_histograms.ijm".Each
#           CSV file contains the following columns: Direction, ROI1, ROI2, ...,
#           Number of frames, Frame interval (sec), Frame rate (per sec), 
#           Pixel size (micron). The ROI columns contain the relative frequency
#           counts for each direction. For each file:
#           1. The dominant directions either side of zero degrees are determined
#              for each ROI, and used to compute the forward and backward speeds
#           2. The speeds are written to "...speed_table.csv"
#           3. Plots of the histogram of directions for each ROI are written to a multipage PDF
#           
# 
#
#  History:  13/02/2023 - V2.1
#

library(pracma)
library(svDialogs)

# Ask user to select a directory containing the CSV files to process
answer = dlg_dir(default = "", title = "Choose the directory containing one or more \"*kymo_direction_histograms.csv\" files to be processed")
src_dir <- answer$res

# Create a list of the CSV files to be processed
csvfiles <- list.files(src_dir, pattern='_kymo_direction_histograms.csv$', recursive=FALSE, full.names = TRUE)

# Process each file in turn
for (i in 1:length(csvfiles)){
  filepathname <- csvfiles[i];
  print(paste("################# Processing file", filepathname))
  
  histogram <- read.table(filepathname,header=TRUE,sep=",",stringsAsFactors = FALSE) # Read in the CSV file
  pixel_size = histogram$Pixel.size..micron.[1]
  frame_interval = histogram$Frame.interval..sec.[1]
  x <- histogram$Direction
  number_of_ROIs <- ncol(histogram) - 5;
  
  forward_speed <- vector();
  backward_speed <- vector();
  
  plotfilepathname <- file.path(dirname(filepathname),paste0(strRep(basename(filepathname),".csv",".pdf")))
  pdf(file = plotfilepathname)
  par(mfrow=c(2,2))
  
  finer_x <- seq(from=-89, to=89, by = 0.5 )
  
  for ( ROI_count in 1:number_of_ROIs) {
    y <- histogram[,1+ROI_count]
    
    if (any(is.nan(y))) {
      print(paste("ROI",ROI_count,"contains NaN values. ROI has been excluded from the speed table"))
      plot(finer_x,rep(0,length(finer_x)))
      next
    }
    
    f_of_x <- splinefun(x,y,method='natural')
    fitted_y <- f_of_x(finer_x)
    
    result<- findpeaks(fitted_y,sortstr = TRUE)
    locn <- result[,2]
    peak_value <- result[,1]
    plot(finer_x,fitted_y,type="l", xlab = "Direction (degrees)", ylab = "Relative frequency", xaxt = 'n') #, main=paste0("ROI",ROI_count))
    axis(1, at = seq(-90, 90, by = 10), las=2)
    #lines(finer_x[locn],peak_value,type="p")
    
    
    # Constant forward speed (i.e. in the direction from the start to the end of a vessel track)
    # generates downward sloping lines in the kymograph. To compute this we need to
    # determine the most dominant negative direction
    location_of_neg_angle_with_largest_peak <- locn[which(finer_x[locn]<=-1)[1]]
    dominant_direction <- finer_x[location_of_neg_angle_with_largest_peak]
    lines(dominant_direction,fitted_y[location_of_neg_angle_with_largest_peak],type="p",col="red")
    #print(dominant_direction)
    tan_theta = tan(abs(dominant_direction)*pi/180) # tan of the angle gives #time_pixels divided by #dist_pixels in the kymograph
    forward_speed[ROI_count] = 1/tan_theta * pixel_size / frame_interval  # speed is (#dist_pixels * pixel_size) divided by (#time_pixels * frame_interval)
    #print(forward_speed[ROI_count])
    
    # Constant backward speed generates upward sloping lines in the kymograph
    location_of_pos_angle_with_largest_peak <- locn[which(finer_x[locn]>=1)[1]]
    dominant_direction <- finer_x[location_of_pos_angle_with_largest_peak]
    #lines(dominant_direction,fitted_y[location_of_pos_angle_with_largest_peak],type="p",col="red")
    #print(dominant_direction)
    tan_theta = tan(abs(dominant_direction)*pi/180)
    backward_speed[ROI_count] = 1/tan_theta * pixel_size / frame_interval  
    #print(backward_speed[ROI_count])
  }
  speed_table <- data.frame(colnames(histogram)[2:(number_of_ROIs+1)],forward_speed,backward_speed)
  
  tablefilepathname <- file.path(dirname(filepathname),paste0(strRep(basename(filepathname),"_kymo_direction_histograms","_speed_table")))
#  write.table(speed_table, tablefilepathname, sep=",", row.names = FALSE)
  dev.off()
  print(paste("Speed table written to",tablefilepathname))
  print(paste("Plots written to", plotfilepathname))
}