Fixed some bugs, imorved error handling