Refactor cofse and add tests