Bunch of fixes. Add perimeter detection.