'overlap' function and some optimization