Re-factored code to make it cleaner