Code refactoring with minor fixes and consistent indentation and style