refactoring and more logic (I should start to test but it's too late)