Redmine/6589

Fix segfault bug, and clean up the code a bit.