def tolerantArrayMatching(referenceArray, matchArray, matchTolerance,
                          matchUnit):
    """#TODO: docstring
    Note: arrays must be sorted

    :param referenceArray: #TODO: docstring
    :param matchArray: #TODO: docstring
    :param matchTolerance: #TODO: docstring
    :param matchUnit: #TODO: docstring

    :returns: #TODO: docstring

    #TODO: change matchUnit to "absolute", "relative" and remove the "*1e-6"
    """
    if matchUnit == 'relative':
        lowLimMatchArr = matchArray * (1 - matchTolerance)
        uppLimMatchArr = matchArray * (1 + matchTolerance)
    elif matchUnit == 'ppm':
        lowLimMatchArr = matchArray * (1 - matchTolerance*1e-6)
        uppLimMatchArr = matchArray * (1 + matchTolerance*1e-6)
    elif matchUnit == 'da':
        lowLimMatchArr = matchArray - matchTolerance
        uppLimMatchArr = matchArray + matchTolerance
    else:
        raise Exception('wrong matchUnit type specified (da or ppm): ',
                        matchUnit)

    lowerLimitMask = numpy.zeros_like(matchArray, dtype=int)
    upperLimitMask = numpy.zeros_like(matchArray, dtype=int)

    refPosLow = int()
    maxReferenceValue = referenceArray[-1]
    for matchPos, (lowerMatch, upperMatch) in enumerate(zip(lowLimMatchArr,
                                                            uppLimMatchArr
                                                            )
                                                        ):
        if lowerMatch < maxReferenceValue:
            while referenceArray[refPosLow] < lowerMatch:
                refPosLow += 1
            refPosHigh = refPosLow
            #Try except statement because this case can only happen once at the
            #end of the array
            try:
                while referenceArray[refPosHigh] <= upperMatch:
                    refPosHigh += 1
            except IndexError:
                refPosHigh = len(referenceArray) - 1
            lowerLimitMask[matchPos] = refPosLow
            upperLimitMask[matchPos] = refPosHigh
        else:
            refPosLow = len(referenceArray) - 1
            refPosHigh = len(referenceArray) - 1
            lowerLimitMask[matchPos] = refPosLow
            upperLimitMask[matchPos] = refPosHigh
            break

    matchPos += 1
    lowerLimitMask[matchPos:len(matchArray)] = refPosLow
    upperLimitMask[matchPos:len(matchArray)] = refPosHigh

    return lowerLimitMask, upperLimitMask