Optimized code and fixed overlap function bug