Refactor and start some unit tests