expandrow(UINT8 *dest, UINT8 *src, int n, int z, int xsize, UINT8 *end_of_buffer) {
    /*
     * n here is the number of rlechunks
     * z is the number of channels, for calculating the interleave
     *   offset to go to RGBA style pixels
     * xsize is the row width
     * end_of_buffer is the address of the end of the input buffer
     */

    UINT8 pixel, count;
    int x = 0;

    for (; n > 0; n--) {
        if (src > end_of_buffer) {
            return -1;
        }
        pixel = *src++;
        if (n == 1 && pixel != 0) {
            return n;
        }
        count = pixel & RLE_MAX_RUN;
        if (!count) {
            return count;
        }
        if (x + count > xsize) {
            return -1;
        }
        x += count;
        if (pixel & RLE_COPY_FLAG) {
            if (src + count > end_of_buffer) {
                return -1;
            }
            while (count--) {
                *dest = *src++;
                dest += z;
            }

        } else {
            if (src > end_of_buffer) {
                return -1;
            }
            pixel = *src++;
            while (count--) {
                *dest = pixel;
                dest += z;
            }
        }
    }
    return 0;
}
expandrow(UINT8 *dest, UINT8 *src, int n, int z, int xsize, UINT8 *end_of_buffer) {
     

    UINT8 pixel, count;
    int x = 0;

    for (; n > 0; n--) {
        if (src > end_of_buffer) {
            return -1;
        }
        pixel = *src++;
        if (n == 1 && pixel != 0) {
            return n;
        }
        count = pixel & RLE_MAX_RUN;
        if (!count) {
            return count;
        }
        if (x + count > xsize) {
            return -1;
        }
        x += count;
        if (pixel & RLE_COPY_FLAG) {
            if (src + count > end_of_buffer) {
                return -1;
            }
            while (count--) {
                *dest = *src++;
                dest += z;
            }

        } else {
            if (src > end_of_buffer) {
                return -1;
            }
            pixel = *src++;
            while (count--) {
                *dest = pixel;
                dest += z;
            }
        }
    }
    return 0;
}