public function sort_categories() {
        $this->attach_nodes_to_categories();
        $tempcategories = array();
        foreach ($this->categories as $category) {
            $after = $category->after;
            if ($after == null) {
                // Can go anywhere in the tree.
                $category->sort_nodes();
                $tempcategories = array_merge($tempcategories, array($category->name => $category),
                        $this->find_categories_after($category));
            }
        }
        if (count($tempcategories) !== count($this->categories)) {
            // Orphan categories found.
            throw new \coding_exception('Some of the categories specified contains invalid \'after\' property');
        }
        $this->categories = $tempcategories;
    }