Bugfix for bug #2480

Also includes some refactoring and partial fixes for bug #68.