public function end_tag($tag) {
        // TODO: check the tag name is valid

        if ($this->level == 0) { // Nothing to end, already at level 0
            throw new xml_writer_exception('xml_writer_end_tag_no_match');
        }

        $pre = $this->lastwastext ? '' : "\n" . str_repeat(' ', ($this->level - 1) * 2); // Indent
        $tag = $this->casefolding ? strtoupper($tag) : $tag; // Follow casefolding

        $lastopentag = array_pop($this->opentags);

        if ($tag != $lastopentag) {
            $a = new stdclass();
            $a->lastopen = $lastopentag;
            $a->tag = $tag;
            throw new xml_writer_exception('xml_writer_end_tag_no_match', $a);
        }

        // Send to xml_output
        $this->write($pre . '</' . $tag . '>');

        $this->level--;
        $this->lastwastext = false;
    }