static byte[] toByteArray(InputStream in, int startSize, int maxSize) throws IOException {
		if (startSize > maxSize) {
			startSize = maxSize;
		}

		// Allocate a buffer
		byte[] buffer = new byte[startSize];

		int pos = 0;
		for (;;) {
			// Copy stream into buffer
			int r = copyStreamToByteArray(in, buffer, pos, buffer.length - pos);

			// We've reached EOF
			if (r == 0) {
				break;
			}

			pos += r;

			// We've filled up a buffer
			if (pos == buffer.length) {
				// Calculate new buffer length
				int newLen = buffer.length * 2;

				// Don't use more than maxSize
				if (newLen > maxSize) {
					newLen = maxSize;
				}

				// Copy into a new buffer
				byte[] newBuffer = new byte[newLen];
				System.arraycopy(buffer, 0, newBuffer, 0, pos);
				buffer = newBuffer;
			}
		}

		// Copy to result array
		if (pos < buffer.length) {
			byte[] newBuffer = new byte[pos];
			System.arraycopy(buffer, 0, newBuffer, 0, pos);
			buffer = newBuffer;
		}

		return buffer;
	}