code refactoring

Now the code grows larger, probably it's the time to revisit our code and do some refactoring, along with some improvements on coding styles and static analysis on code to find potential bugs, and add more run-time check to make sure code works as our expected...