public byte[] writePhotoshopApp13Segment(PhotoshopApp13Data data)
            throws IOException, ImageWriteException
    {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        BinaryOutputStream bos = new BinaryOutputStream(os);

        bos.write(PHOTOSHOP_IDENTIFICATION_STRING);

        List blocks = data.getRawBlocks();
        for (int i = 0; i < blocks.size(); i++)
        {
            IPTCBlock block = (IPTCBlock) blocks.get(i);

            bos.write(CONST_8BIM);

            if (block.blockType < 0 || block.blockType > 0xffff)
                throw new ImageWriteException("Invalid IPTC block type.");
            bos.write2ByteInteger(block.blockType);

            if (block.blockNameBytes.length > 255)
                throw new ImageWriteException("IPTC block name is too long: "
                        + block.blockNameBytes.length);
            bos.write(block.blockNameBytes.length);
            bos.write(block.blockNameBytes);
            if (block.blockNameBytes.length % 2 == 0)
                bos.write(0); // pad to even size, including length byte.

            if (block.blockData.length > IPTC_NON_EXTENDED_RECORD_MAXIMUM_SIZE)
                throw new ImageWriteException("IPTC block data is too long: "
                        + block.blockData.length);
            bos.write4ByteInteger(block.blockData.length);
            bos.write(block.blockData);
            if (block.blockData.length % 2 == 1)
                bos.write(0); // pad to even size

        }

        bos.flush();
        return os.toByteArray();
    }