class VOIUtils {

    public static DicomObject selectVoiObject(DicomObject img, DicomObject pr, int frame) {
        String iuid = img.getString(Tag.SOPInstanceUID);
        DicomObject voi = selectVoiItemFromPr(iuid, pr, frame);
        if (voi != null) {
            return voi;
        }
        if (pr != null) {
            return pr;
        }

        DicomElement framed = img.get(Tag.PerFrameFunctionalGroupsSequence);
        if (framed != null) {
            int size = framed.countItems();
            if (frame >= 1 && frame <= size) {
                DicomObject frameObj = framed.getDicomObject(frame - 1);
                if (frameObj != null) {
                    DicomObject voiObj = frameObj.getNestedDicomObject(Tag.FrameVOILUTSequence);
                    if (voiObj != null && containsVOIAttributes(voiObj)) {
                        return voiObj;
                    }
                }
            }
        }
        DicomObject shared = img.getNestedDicomObject(Tag.SharedFunctionalGroupsSequence);
        if (shared != null) {
            DicomObject voiObj = shared.getNestedDicomObject(Tag.FrameVOILUTSequence);
            if (voiObj != null && containsVOIAttributes(voiObj)) {
                return voiObj;
            }
        }
        if (containsVOIAttributes(img))
            return img;
        return null;
    }

}

class VOIUtilsTest {

    @Test
    public void testSelectVOIObjectShouldReturnSharedFrameDataIfPerFrameDataIsNotPresent() {

        DicomObject sharedVoiLut = createWindowCenterObject();
        DicomObject obj = new BasicDicomObject();
        DicomElement frameGroupSequence = obj.putSequence(Tag.PerFrameFunctionalGroupsSequence);
        addFrame(frameGroupSequence, null);
        addFrame(frameGroupSequence, null);
        obj.putNestedDicomObject(Tag.SharedFunctionalGroupsSequence,
                createFrameGroups(sharedVoiLut));

        assertSame(sharedVoiLut, VOIUtils.selectVoiObject(obj, null, 2));
    }

}