Code refactor. Needs debug