Some refactoring, added listener code