#!/usr/bin/env ruby

require 'csv'

def process_kfn(file)
  # Check if the file exists
  unless File.exist?(file)
    raise "File not found: #{file}"
  end

  # Read the file contents
  file_contents = CSV.read(file, col_sep: "\t")

  # Generate bpm and start_time
  bpm = generate_bpm(file_contents)
  start_time = generate_start_time(file_contents)

  [bpm, start_time]
end

def generate_bpm(file_contents)
  # Look at only the first 8 rows for BPM calculation
  rows = file_contents.first(8)

  # Calculate the deltas (differences in the 2nd column values)
  deltas = rows.each_cons(2).map do |row1, row2|
    row2[1].to_f - row1[1].to_f
  end

  # Average the deltas and convert to BPM
  average_delta = deltas.sum / deltas.size
  bpm = (1 / average_delta) * 60

  bpm.round(2) # Return rounded BPM value
end

def generate_start_time(file_contents)
  # Return the 2nd column value of the first row
  file_contents.first[1].to_f
end

if __FILE__ == $0
  # Main script execution
  if ARGV.size != 1
    puts "Usage: #{$PROGRAM_NAME} <kfn_file>"
    exit 1
  end

  kfn_file = ARGV[0]

  begin
    bpm, start_time = process_kfn(kfn_file)
    puts "BPM: #{bpm}"
    puts "Start Time: #{start_time}"
  rescue => e
    puts "Error: #{e.message}"
  end
end
