Do more refactoring and code cleanup.

Unfortunately I don't remember detailed description of this chages.