Massive code refactoring, simplification and cleanup