protected List insertBeforeFirstAppSegments(List segments, List newSegments)
            throws ImageWriteException
    {
        int firstAppIndex = -1;
        for (int i = 0; i < segments.size(); i++)
        {
            JFIFPiece piece = (JFIFPiece) segments.get(i);
            if (!(piece instanceof JFIFPieceSegment))
                continue;

            JFIFPieceSegment segment = (JFIFPieceSegment) piece;
            if (segment.isAppSegment())
            {
                if (firstAppIndex == -1)
                    firstAppIndex = i;
            }
        }

        List result = new ArrayList(segments);
        if (firstAppIndex == -1)
            throw new ImageWriteException("JPEG file has no APP segments.");
        result.addAll(firstAppIndex, newSegments);
        return result;
    }