updated to better encapsulate within a function closure; added comments