There's some code smell here with

1) Option types that are kept as Some[pileup] throughout the duration of the flatMap
2) variables modified on each iteration of a flatMap