Refactored and tried my best to implement overlap checking