Refined the code and added more comments