Refactoring code,rearrange functions