Refactor and improve testing