Code cleanup and better test coverage