def truncate_roi(orig_roi, src_image_size):
    """
    Returns truncated ROI for source and destination images. Crops ROI so that
    image edges are handled correctly.
    """
    # Set x position of ROI
    if orig_roi[0] < 0:
        src_x = 0
        dst_x = -orig_roi[0]
        w = orig_roi[2] + orig_roi[0]
    else:
        src_x = orig_roi[0]
        dst_x = 0
        w = orig_roi[2]

    # Set y position of ROI
    if orig_roi[1] < 0:
        src_y = 0
        dst_y = -orig_roi[1]
        h = orig_roi[3] + orig_roi[1]
    else:
        src_y = orig_roi[1]
        dst_y = 0
        h = orig_roi[3]

    # Set width of ROI
    if (src_x + w) >= src_image_size[0]:
        w = src_image_size[0] - src_x - 1

    # Set height of ROI
    if (src_y + h) >= src_image_size[1]: 
        h = src_image_size[1] - src_y - 1

    # Create source and destiniatin image ROI's
    src_roi = src_x, src_y, w, h
    dst_roi = dst_x, dst_y, w, h

    return src_roi, dst_roi