Refactor, add fns and tests