Reapplying Perimeter Dectection Fix

I accidentally overwrote the fix from few commits ago. There's no
excuse. I can only beg forgiveness.