A working version (works at least for me in my app, not sure about resource leaks, etc.)