refactored a little bit to allow registration of callbacks