add new code from hauke
it seems haukes' as well as my code works now.
haukes' looks a lot better, though.
i improved a few test cases.