More unit tests and fix some logic