You are using Math.atan incorrectly here.
I think you meant to use Math.atan2 (which is a more standard function although it has that 2 at the end).
It has two major benefits
fixed issues #1 and #2
I have replaced atan with atan2, code looks much more clear now.
Thanks for reviewing my code,