protected void writeToStream(final InputStream in, final OutputStream out)
			throws XMPPException
    {
		final byte[] b = new byte[BUFFER_SIZE];
		int count = 0;
		amountWritten = 0;

        do {
			// write to the output stream
			try {
				out.write(b, 0, count);
			} catch (IOException e) {
				throw new XMPPException("error writing to output stream", e);
			}

			amountWritten += count;

			// read more bytes from the input stream
			try {
				count = in.read(b);
			} catch (IOException e) {
				throw new XMPPException("error reading from input stream", e);
			}
		} while (count != -1 && !getStatus().equals(Status.cancelled));

		// the connection was likely terminated abrubtly if these are not equal
		if (!getStatus().equals(Status.cancelled) && getError() == Error.none
				&& amountWritten != fileSize) {
            setStatus(Status.error);
			this.error = Error.connection;
		}
	}