Cleanup and some refactoring