Major rewrite of metadata handling.

Now much more compliant with Metadata Working Group guidelines, and
better structured.