Add proper handling of recursive classes

Add functionality that handles references to the current object (or
object objects "higher up") to avoid endless recursive loops!

Also reorganise the methods of ktExport to promote modular design and
avoid duplication of code.