require 'thread'

def filter(in_file, out_file)
	raise "Block needed" unless block_given?

	h = File.open(out_file, 'w')
	IO.foreach(in_file) { |row|
		data = row.split(',').map { |i| i.to_f }
		new_columns = [yield(data)].flatten
		h.write "#{row.strip},#{new_columns.join(',')}\n"
#		puts "#{row.strip.gsub ',', "\t"}\t#{new_columns.join("\t")}\n"
	}
end

def boolean_filter(in_file, out_file)
	raise "Block needed" unless block_given?

	h = File.open(out_file, 'w')
	IO.foreach(in_file) { |row|
		data = row.split(',').map { |i| i.to_f }
		new_columns = [yield(data)].flatten.map { |i| (i)?1.0:0.0 }
		h.write "#{row.strip},#{new_columns.join(',')}\n"
	}
end

def matching_segment_length(in_file, out_file, negative_falses = true)
	raise "Block needed" unless block_given?
	
	rows = Queue.new
	h = File.open(out_file, 'w')
	last_value = nil
	
	IO.foreach(in_file) { |row|
		data = row.split(',').map { |i| i.to_f }
		value = yield(data)
		if (not last_value.nil?) && value != last_value
			length = rows.length
			length = 0.0 - length if negative_falses && (not last_value)
			while not rows.empty?
				h.write "#{rows.pop.strip},#{length}\n"
			end
		end
		rows.push row
		last_value = value
	}
	
	length = rows.length.to_f
	length = 0.0 - length if negative_falses && (not last_value)
	while not rows.empty?
		h.write "#{rows.pop.strip},#{length}\n"
	end
end

def replicate(in_file, out_file, data)
	data = [data].flatten
	h = File.open(out_file, 'w')
	IO.foreach(in_file) { |row|
		h.write "#{row.strip},#{data.join(',')}\n"
	}
end
