Collections.sort(unusedElements, TiffElement.COMPARATOR);
Collections.reverse(unusedElements);
// any items that represent a gap at the end of the exif segment, can be discarded.
while (unusedElements.size() > 0)
{
TiffElement element = (TiffElement) unusedElements.get(0);
int elementEnd = element.offset + element.length;
if (elementEnd == overflowIndex)
{
// discarding a tail element. should only happen once.
overflowIndex -= element.length;
unusedElements.remove(0);
}
else
break;
}
Collections.sort(unusedElements, ELEMENT_SIZE_COMPARATOR);
Collections.reverse(unusedElements);
// Debug.debug("unusedElements");
// dumpElements(unusedElements);
// make copy.
List unplacedItems = new ArrayList(outputItems);
Collections.sort(unplacedItems, ITEM_SIZE_COMPARATOR);
Collections.reverse(unplacedItems);
while (unplacedItems.size() > 0)
{
// pop off largest unplaced item.
TiffOutputItem outputItem = (TiffOutputItem) unplacedItems
.remove(0);
int outputItemLength = outputItem.getItemLength();
// Debug.debug("largest unplaced item: "
// + outputItem.getItemDescription() + " (" + outputItemLength
// + ")");
// search for the smallest possible element large enough to hold the item.
TiffElement bestFit = null;
for (int i = 0; i < unusedElements.size(); i++)
{
TiffElement element = (TiffElement) unusedElements.get(i);
if (element.length >= outputItemLength)
bestFit = element;
else
break;
}