And everything works correctly.

Seems that the stupid error was indeed stupid. In test2, the
angle theta is between 0 and 2/3 pi but acos works between 0
and pi, so that was incorrect.
some cleaning up and comments