rewrite for cleaner codes

No logic change, only code styles or minor refactorings.