public function addOrderBy($clauses = null, $direction = null)
    {
        if (empty($clauses)) {
            return $this;
        }

        if (is_string($clauses)) {
            if (strpos($clauses, "(") !== false) {
                $sort = preg_split("/,(?![^()]*+\\))/", $clauses);
            } else {
                $sort = explode(",", $clauses);
            }

            $clauses = array();

            foreach ($sort as $clause) {
                list($column, $direction) = $this->getDirectionFromString($clause, $direction);
                $clauses[$column] = $direction;
            }
        }

        if (is_array($clauses)) {
            foreach ($clauses as $key => $value) {
                if (!is_numeric($key)) {
                    $column = trim($key);
                    $columnDir = strtoupper(trim($value));
                } else {
                    list($column, $columnDir) = $this->getDirectionFromString($value);
                }

                $this->orderby[$column] = $columnDir;
            }
        } else {
            user_error('SQLSelect::orderby() incorrect format for $orderby', E_USER_WARNING);
        }

        // If sort contains a public function call, let's move the sort clause into a
        // separate selected field.
        //
        // Some versions of MySQL choke if you have a group public function referenced
        // directly in the ORDER BY
        if ($this->orderby) {
            $i = 0;
            $orderby = array();
            foreach ($this->orderby as $clause => $dir) {
                // public function calls and multi-word columns like "CASE WHEN ..."
                if (strpos($clause, '(') !== false || strpos($clause, " ") !== false) {
                    // Move the clause to the select fragment, substituting a placeholder column in the sort fragment.
                    $clause = trim($clause);
                    do {
                        $column = "_SortColumn{$i}";
                        ++$i;
                    } while (array_key_exists('"' . $column . '"', $this->orderby));
                    $this->selectField($clause, $column);
                    $clause = '"' . $column . '"';
                }
                $orderby[$clause] = $dir;
            }
            $this->orderby = $orderby;
        }

        return $this;
    }