Reorganize logic to make code more clear