cleaned up code and added comments for cycle detection