Re-factored the code