 			
 			stream.next_in = data;
 			stream.next_in_index = 0;
+			stream.avail_in = data.length;
 			
 			stream.next_out = compressed;
 			stream.next_out_index = 0;
-			
-			
-			// ----
-			
-			var comprLen:int = 40000;
-			while (stream.total_in != data.length && stream.total_out < comprLen)
-			{
-				// force small buffers
-				stream.avail_in = 1;
-				stream.avail_out = 1;
-				
-				err = stream.deflate(JZlib.Z_NO_FLUSH);
-				checkError(stream, err, "deflate");
-			}
-			
-			while (true)
-			{
-				stream.avail_out = 1;
-				err = stream.deflate(JZlib.Z_FINISH);
-				if (err == JZlib.Z_STREAM_END)
-				{
-					break;
-				}
-
-				compressed.position = 0;
-				
-				checkError(stream, err, "deflate");
-			}
-			
-			err = stream.deflateEnd();
-			checkError(stream, err, "deflateEnd");
-	
+			stream.avail_out = outLen;
+			
+			
+			
+			
+			
+			err = stream.deflate(JZlib.Z_SYNC_FLUSH);
+			
+			if (err != JZlib.Z_OK)
+			{
+				compressed = null;
+				trace("Zlib.compress. Compression failed with return value : " + err);
+			}
+			
+			
+			// TODO: we need this, but why? zlib must be missing something
+			
+			if (compressed.length > 2)
+			{
+				compressed.position = compressed.length - 2;
+				compressed.writeByte(0xFF);
+				compressed.writeByte(0xFF);
+			}
+			
+			
 			
 			trace("Zlib.compress. compressed.length: " + compressed.length);
 			trace("Zlib.compress. compressed: " + compressed.toString());

						trace("Zlib.uncompress. inflation stream ended");
						break;
					case JZlib.Z_BUF_ERROR:
						stream.next_out_index = 0;
						stream.avail_out = outBytesLength;
						break;

			}
			return true;
		}
		
		private function emptyByteArrayIntoByteArray(chunk:ByteArray, target:ByteArray):void
		{
			for (var j:uint = 0; j < chunk.length; j++)
			{
				target.writeByte(chunk.readByte());
			}
			chunk.clear();
		}
	}
}
