Major code cleanup and some minor refactoring