Various bugfix, and some new code.