Full code refactor + add external function