Fix handling of multiple relations. Also, code cleanup.