Quaternion Decomposition I'm having trouble decomposing a unit quaternion into euler angles (or roll, pitch and yaw). The overall goal is to tell how a phone is rotated with respect to the world. I'm given a unit quaternion this world axis:

The axis has the following characteristics:


*

*X is defined as the vector product Y.Z (It is tangential to the ground at the device's current location and roughly points East).

*Y is tangential to the ground at the device's current location and points towards magnetic north.

*Z points towards the sky and is perpendicular to the ground.


DISCLAIMER: Trying to find the rotation around the z-axis by using atan2(y-component of quaternion, x-component of quaternion) without involving the phone at all, the angle is always between 180 and 360 degrees. Since I'm very new to working with quaternions, I'm trying to figure out whether my error is in the math, or in my code.
I have the following phone axis: 

The phone will be held in landscape mode rotated 90 degrees counterclockwise around the z-axis. I need the angle of rotation around the world's z-axis (to see which direction the user is facing), the angle of rotation about the world's y-axis (to determine the angle off of the horizon), and the angle of rotation about the x-axis (to see whether the device is horizontal to the ground).
 A: Okay, so you have an East-North-Down coordinate system as the fixed frame, and you have the phone's Up-Left-Out (of the screen) set of axes, and the quaternion is given in terms of the fixed coordinate system's basis vectors.  I'll call the fixed axes $\hat x, \hat y, \hat z$ and the phone's axes $\hat x', \hat y', \hat z'$.
If you're using the phone as a camera, then I imagine it's the phone's Out-of-screen direction that is most like the direction the camera is facing (or rather, the negative of this).  So the vector $-\hat z'$ should be the direction that the camera is facing.  You should then project this vector onto the $xy$-plane by zeroing out its $\hat z$ component:  $P_{xy}(\hat z') = \hat z' - \hat z (\hat z \cdot \hat z')$.  You can then renormalize the result and find the angle in the $xy$-plane by basic trig.  This should give you the compass direction that the camera is pointing (as an angle relative to east).
Angle off the horizon is easier.  Take $-\hat z' \cdot \hat z = \cos \theta$.  $\theta$ is then the angle off the vertical.  $\theta - \pi/2$ should then give the angle you want:  if $\theta = \pi/2$, then the camera is level.  If it's larger, then the camera is tilted upwards.  That checks out.
I admit, I'm not sure why you want to know if the device is horizontal to the ground; it's not clear to me how this relates to the direction of the camera, and so I'm not sure what answer to give for that part.
