Imported new code

May not compile due to missing classes, but code comes from a "almost"
working copy