#!/usr/bin/python3

# 100 2 1200000 0 0.513801

import fileinput, operator, sys

def printKeysRecursive(a, depth=0):
	for key in sorted(a.keys()):
		for space in range(depth):
			print("\t", end="")
		print(key, end="")
		if (isinstance(a[key], dict)):
			print()
			printKeysRecursive(a[key], depth+1)
		else:
			print(" = {}".format(a[key]))

def search(data, hint, searchRange, func):
	if (hint is None):
		return None
	iterlist = sorted(data.keys())
	start = hint[0] - searchRange
	stop = hint[0] + searchRange
	candidates = []
	for key in iterlist:
		if (key >= start and key <= stop):
			candidates.append((key, data[key]))
	if (len(candidates) > 0):
		if (func == "min"):
			rval = min(candidates, key=operator.itemgetter(1))
			if (rval[1] <= hint[1]):
				return rval
		elif (func == "max"):
			rval = max(candidates, key=operator.itemgetter(1))
			if (rval[1] >= hint[1]):
				return rval
	return None

if (len(sys.argv) != 5):
	print("Usage: swoosh.py <a>,<b>,<c>,... <start-a>,<start-b> <range-b> <min|max>")
	sys.exit(1)

data = {}
dim = 0

print("Reading point data")
for line in fileinput.input("-"):
	line = line.strip()
	if (len(line)):
		point = line.split()
		if (dim == 0):
			dim = len(point)
			if (dim < 2):
				print("Use at least 2D data")
				sys.exit(1)
		elif (dim != len(point)):
				print("Dimensional inconsistency, aborting.  Check your input data set for corruption.")
				sys.exit(1)
		try:
			for i in range(dim):
				point[i] = float(point[i])
		except ValueError as ex:
			print("Unable to convert string [{}] to float".format(point[i]))
			raise
		a = data
		for i in range(dim - 1):
			if (i < dim - 2):
				if (point[i] not in a):
					a[point[i]] = dict()
				a = a[point[i]]
			else:
				a[point[i]] = point[i+1]

subset = data
scope = sys.argv[1].split(",")
for i in scope:
	subset = subset[float(i)]
searchRange = float(sys.argv[3])
start = [float(i) for i in sys.argv[2].split(",")]
if (sys.argv[4] == "min"):
	result = (start[1], float("inf"))
elif (sys.argv[4] == "max"):
	result = (start[1], float("-inf"))
else:
	print("Specify <min|max> for the last argument")
	sys.exit(1)

#printKeysRecursive(subset)
iterlist = sorted(subset.keys())
for a in iterlist[iterlist.index(start[0]):]:
	if (sys.argv[4] == "min"):
		result = search(subset[a], result, searchRange, "min")
	elif (sys.argv[4] == "max"):
		result = search(subset[a], result, searchRange, "max")
	if (result is None):
		break
	print("{} {} {}".format(a, result[0], result[1]))

