Refactor and add fns and tests