Big rewrite to support different descriptor types.
Rearranged everything and deleted obsolete code.