Cleaned up the function and added proper comments.