optimized recurrence code (I hope)