optimized code to not enter not optimal paths