Add some UTs and do a little refactoring