Refactoring of the code as per @revett's comments