rewrite for cleaner codes

No logic change, only code styles or minor refactorings.
I want to note that this part is important. I'll look more into it!