numerous bugfixes + refactors
numerous bugfixes and refactors