// Code is under the zlib license (same as Irrlicht)
// Written by Michael Zeilfelder
// 
// Search bug in: http://i...content-available-to-author-only...e.net/forum/viewtopic.php?f=7&t=50620

#include <irrlicht.h>
#include <cassert>

using namespace irr;
using namespace core;

#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif

core::vector3df anotherConversion(const quaternion& q)
{
	irr::f32 test = q.X*q.Y + q.Z*q.W;
	if (test > 0.499) { // singularity at north pole
		return core::vector3df(2 * atan2(q.X,q.W), PI/2.f, 0);
	}
	if (test < -0.499) { // singularity at south pole
		return core::vector3df(-2 * atan2(q.X,q.W), - PI/2.f, 0);
	}
    irr::f32 sqx = q.X*q.X;
    irr::f32 sqy = q.Y*q.Y;
    irr::f32 sqz = q.Z*q.Z;
    return core::vector3df(atan2(2.f*q.Y*q.W-2.f*q.X*q.Z, 
							1.f - 2.f*sqy - 2.f*sqz), asin(2.f*test), 
							atan2(2.f*q.X*q.W-2.f*q.Y*q.Z , 1.f - 2.f*sqx - 2.f*sqz));
}

int main(int argc, char *argv[])
{
	quaternion q1,q2;
	q1.set(core::vector3df(0, 90, 0) *DEGTORAD);
	q2.set(core::vector3df(0, 91, 0) *DEGTORAD);
	core::vector3df e1, e2;
	q1.toEuler(e1);
	e1 *= RADTODEG;
	q2.toEuler(e2);
	e2 *= RADTODEG;
	core::vector3df e3(anotherConversion(q2));
	e3 *= RADTODEG;

	return 0;
}
