complete logic, needs refactoring