Refactor funcs and write test