Clean up some code, refactor and beef up tests