Code cleanup - major refactoring