# -*- coding: utf-8 -*-
# From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/285264
# Licensed under PSF: http://python.org/license

import re
import copy


def try_int(s):
    "Convert to integer if possible."
    try: return int(s)
    except: return s

def natsort_key(s):
    "Used internally to get a tuple by which s is sorted."
    return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):
    "Natural string comparison, case sensitive."
    return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
    "Natural string comparison, ignores case."
    return natcmp(a.lower(), b.lower())

def natsort(seq, cmp=natcmp):
    "In-place natural string sort."
    seq.sort(cmp)

def natsorted(seq, cmp=natcmp):
    "Returns a copy of seq, sorted by natural string sort."
    temp = copy.copy(seq)
    natsort(temp, cmp)
    return temp

def obj_natsorted(seq, cmp, key):
    d = dict([(key(i), i) for i in seq])
    sorted = natsorted(d.keys(), cmp)
    return [ d[k] for k in sorted ]
