major refactoring and bug squashing