use lastPos to avoid repeated calculations and improve readability