minor corrections and some refactorings to make the code more readable