Fixes some bugs and adds test to cover them.