Changed from atan to atan2 to avoid numerical problems in dividing tphi/ty