Code refactoring and minor bugs fixed