Re-structured code for readability and added comments.