a little bit of cleanup and added comments for readability