Reafctoring and bugfixes.