some improvements and error handling