Add unit tests and code fixes