rewrite to fully support events and error handling