Improved calculateNext function