Separated eachtotal gathering process into a function.

However, there may still be problems.