several improvements and bugfixes. (not fully tested.)