Lots of bugfixes.
Added initial support for threading.