1. refactoring: using double instead of int for better precision
2. minor bug fixes and sanity checks