refactoring and rearrange code