Refactored context somewhat to make it easier to port to XML.