error handling, restructure and cleanup