Added logic to handle negatively sloped lines in the final algorithm.