cleaned up code. added comments. hopefully logic is easier to follow