some cleanups and error handling optimisation