Reorganize logic to make code more clear.

Reorganize logic to make code more clear.