public function resolve(ReferenceContext $context = null)
    {
        if ($context === null) {
            $context = $this->getContext();
            if ($context === null) {
                throw new UnresolvableReferenceException('No context given for resolving reference.');
            }
        }
        if (($pos = strpos($this->_ref, '#')) === 0) {
            // resolve in current document
            $jsonPointer = substr($this->_ref, 1);
            // TODO type error if resolved object does not match $this->_to ?
            return $this->resolveJsonPointer($jsonPointer, $context->getBaseSpec());
        }

        $file = ($pos === false) ? $this->_ref : substr($this->_ref, 0, $pos);
        $file = $context->resolveRelativeUri($file);
        $jsonPointer = ($pos === false) ? '' : substr($this->_ref, $pos + 1);

        // TODO could be a good idea to cache loaded files in current context to avoid loading the same files over and over again
        $fileContent = $this->fetchReferencedFile($file);
        $referencedData = $this->resolveJsonPointer($jsonPointer, $fileContent);

        /** @var $referencedObject SpecObjectInterface */
        $referencedObject = new $this->_to($referencedData);
        if ($jsonPointer === '') {
            $referencedObject->setReferenceContext(new ReferenceContext($referencedObject, $file));
        } else {
            // TODO resolving references recursively does not work as we do not know the base type of the file at this point
//            $referencedObject->resolveReferences(new ReferenceContext($referencedObject, $file));
        }

        return $referencedObject;
    }