fixed several bugs: error handlingand resource release