Refactoring and bug fix

This code was modified for organization propose.