def _best_rect_ratio_match(bricks, size, margin):
    """ Sort and filter list of bricks based on target ration and margin

    'margin' determines how easily a brick passes filtering. Results are sorted
    from best matching to worst before returning the list.

    """

    def _ratio(_size):
        if _size[1] == 0:
            return 0
        else:
            return _size[0] / _size[1]

    target_ratio = _ratio(size)

    bricks = filter(lambda x: abs(_ratio(x['dimensions']) - target_ratio) < target_ratio * margin, bricks)
    return sorted(bricks, key=lambda x: abs(_ratio(x['dimensions']) - target_ratio))