Fixed some bugs and added proper exceptions handling