Clean up script.

Made the math a bit more obvious, and added more checks.