reverting previous commit and re-refactoring code.
Fixing potential NRE