added comments into the functions to describe the flow