optimizing code, some bugfixes