Implemented cleanups and fixes as suggested by Miroslav Fuksa.
Not sure if I got the thread safeness right.