Some optimization and bugfixes