finish refactoring many of the ugly code, a little more compact now