public static function sortHeaders($messages, $field, $flag)
    {
        // Strategy: First, we'll create an "index" array.
        // Then, we'll use sort() on that array, and use that to sort the main array.

        $field  = empty($field) ? 'uid' : strtolower($field);
        $flag   = empty($flag) ? 'ASC' : strtoupper($flag);
        $index  = array();
        $result = array();

        reset($messages);

        foreach ($messages as $key => $headers) {
            $value = null;

            switch ($field) {
            case 'arrival':
                $field = 'internaldate';
            case 'date':
            case 'internaldate':
            case 'timestamp':
                $value = rcube_utils::strtotime($headers->$field);
                if (!$value && $field != 'timestamp') {
                    $value = $headers->timestamp;
                }

                break;

            default:
                // @TODO: decode header value, convert to UTF-8
                $value = $headers->$field;
                if (is_string($value)) {
                    $value = str_replace('"', '', $value);
                    if ($field == 'subject') {
                        $value = preg_replace('/^(Re:\s*|Fwd:\s*|Fw:\s*)+/i', '', $value);
                    }

                    $data = strtoupper($value);
                }
            }

            $index[$key] = $value;
        }

        if (!empty($index)) {
            // sort index
            if ($flag == 'ASC') {
                asort($index);
            }
            else {
                arsort($index);
            }

            // form new array based on index
            foreach ($index as $key => $val) {
                $result[$key] = $messages[$key];
            }
        }

        return $result;
    }