Some fixes

Fixes some crashes and infinite loops.

Please also have a look at the TODO comment.