Fix some bugs and add error checking