Bugfixes on logic and thread safety