Fix several bugs and introduce functional tests