a few bugfixes and cleanup
fix significant bugs which caused backtracking, and code cleanup