A bunch of refactoring - more testing needed