Added cycle detection, discovered a bug