"""abbSchwartz.py

This is a Python implementation for abbSchwartz

Functions:
find    Find all the abbreviations in a string.

"""
def find(string):
    """find(string) -> list of (long form, short form)"""
    from Extracto.abbreviation import candidate
    string = str(string)
    abbs = []
    candidates = candidate.find(string)
    for long_form, short_form, long_form_grows in candidates:
        long_form = findBestLongForm(short_form, long_form)
        if not long_form:
            continue
        abbs.append((long_form, short_form))
    return abbs

def findBestLongForm(shortForm, longForm):
    """findBestLongForm(shortForm, longForm) -> best long form or None"""
    from Extracto import ctype
    
    sIndex = len(shortForm) - 1
    lIndex = len(longForm) - 1

    for sIndex in range(sIndex, -1, -1):
        currChar = shortForm[sIndex].lower()
        if not ctype.isalnum(currChar):
            continue

        while (lIndex >= 0 and longForm[lIndex].lower() != currChar) or \
              (sIndex == 0 and lIndex > 0 and
               ctype.isalnum(longForm[lIndex-1])):
            lIndex -= 1
        if lIndex < 0:
            return None
        lIndex -= 1
    lIndex = longForm.rfind(" ", 0, lIndex+1)+1
    return longForm[lIndex:]
