public function addIndex($index, $after=null) {

        // Detect duplicates first
        if ($this->getIndex($index->getName())) {
            throw new coding_exception('Duplicate index '.$index->getName().' specified in table '.$this->getName());
        }

        // Make sure there are no keys with the index column specs because they would collide.
        $newfields = $index->getFields();
        $allkeys = $this->getKeys();
        foreach ($allkeys as $key) {
            $fields = $key->getFields();
            if ($fields === $newfields) {
                throw new coding_exception('Key '.$key->getName().' collides with index'.$index->getName().' specified in table '.$this->getName());
            }
        }

        // Calculate the previous and next indexes
        $previndex = null;
        $nextindex = null;

        if (!$after) {
            $allindexes = $this->getIndexes();
            if (!empty($allindexes)) {
                end($allindexes);
                $previndex = $allindexes[key($allindexes)];
            }
        } else {
            $previndex = $this->getIndex($after);
        }
        if ($previndex && $previndex->getNext()) {
            $nextindex = $this->getIndex($previndex->getNext());
        }

        // Set current index previous and next attributes
        if ($previndex) {
            $index->setPrevious($previndex->getName());
            $previndex->setNext($index->getName());
        }
        if ($nextindex) {
            $index->setNext($nextindex->getName());
            $nextindex->setPrevious($index->getName());
        }

        // Some more attributes
        $index->setLoaded(true);
        $index->setChanged(true);
        // Add the new index
        $this->indexes[] = $index;
        // Reorder the indexes
        $this->orderIndexes($this->indexes);
        // Recalculate the hash
        $this->calculateHash(true);
        // We have one new index, so the table has changed
        $this->setChanged(true);
    }