nickw's auth stuff, plus some optimisations. If f--king svn finally commits this...