fix nits, bugs and extend unit test