added more descriptive commenting, and moved some code around