#!/usr/bin/python
"""
Converts x y z l format to a e l.
With -d it converts it to e a d l.
Elevation range is -90,90.
Azimuth range is 0,360.
Comments are left as is.
Labels may be empty.
Spaces and tabs in labes collapsed into one space.
Non comments lines with less than 2 columns are ignored and a waring is raised.
"""

import sys, math


def at360(degrees) :
	while degrees<0 : degrees+=360
	while degrees>360 : degrees-=360
	return degrees

def conventionEA(e, a) :
	e += 90.;
	e = at360(e)
	if e>180.+1e-13 :
		a += 180;
		e = 360 - e;
	a = at360(a);
	e -= 90;
	return e,a

def xyz2ea(input, output, dumpDistance=False) :
#	print "# Generated by xyz2ead"
	for i, line in enumerate(input.readlines()) :
		tokens = line.split()
		# Comments are left as is
		if line[0]=='#' :
			print line
			continue
		if len(tokens) < 3 :
			print >> sys.stderr, "Ignoring line", i
			continue
		x,y,z = float(tokens[0]), float(tokens[1]), float(tokens[2])
		label = "%02i"%(i+1) if len(tokens)<4 else " ".join(tokens[3:])
		d = math.sqrt(x*x + y*y + z*z)
		a = math.degrees(math.atan2(y,x))
		e = math.degrees(math.asin(z/d))
		e, a = conventionEA(e,a)
		if '-d' in sys.argv :
			print >> output, e, a, d, label
		else :
			print >> output, e, a, label
if __name__ == '__main__' :
	xyz2ea(sys.stdin, sys.stdout, '-d' in sys.argv)



