Reorganized the functions and added comments.