cleaned up code, many bugfixes and some tests