Code cleanup and some refactorings