improved end handling, and optimized the algorithm