Improved the logic for reversing motion.