Rewrite boundaries detection

This is running much faster than the current implementation.