#!/usr/bin/ruby
require 'yaml'
require './stats.rb'

if ARGV.empty?
	puts "Usage: ./lpf_rules.rb test.csv [bins]"
	exit
end

data_file = ARGV.shift
bins = (ARGV.shift || 20).to_i

h = File.open(data_file, 'r')
column_names = h.readline.strip.split(',')
lpf_column_ids = %w{lpf_x lpf_y lpf_z}.map { |i| column_names.index i }
evt_column_id = column_names.index 'event3'

s = stats(data_file, lpf_column_ids)

min = s['min']
max = s['max']
lens = [*0..2].map { |i| max[i] - min[i] }
bin_lens = lens.map { |l| 1.001 * l / bins } # a small fix for maximum values
bin_prefixes = %w{x y z}

while (not h.eof?)
	data = h.readline.split(',').map { |i| i.to_f }
	event_on = data[evt_column_id] > 0.5
	
	selected_bins = lpf_column_ids.each_with_index.map { |col_i, i|
		bin = ((data[col_i] - min[i]) / bin_lens[i]).to_i
		if bin < 0
			puts "Bin below scale, setting to 0."
			bin = 0
		elsif bins <= bin
			puts "Bin above scale, setting to #{bins - 1}."
			bin = bins - 1
		end
		"#{bin_prefixes[i]}_bin_#{bin}"
	}
	puts "#{selected_bins.join ' '} #{event_on}"
end
