Refactoring code to make more readable

Refactoring the code into separate function remove some nesting and make
code more readable. Removed any default formatters.