Add unit test

As well as minor changes and a bug fix.