refactor, additional tests, and better security