added comments and changed code slightly from orginal