Improved Cycle Detection

Refactored to support improved cycle detection and contains many bugfixes.