--- tools/cws2fws.c.orig	2007-07-19 00:38:04.000000000 +0900
+++ tools/cws2fws.c	2010-07-05 08:02:17.000000000 +0900
@@ -39,7 +39,7 @@
         exit(1);
     }
 
-    fd_out = open(argv[2], O_WRONLY|O_CREAT, 00644);
+    fd_out = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 00644);
     if (fd_out < 0)
     {
         perror("Error while opening: ");
@@ -63,7 +63,7 @@
 
     fstat(fd_in, &statbuf);
     comp_len = statbuf.st_size;
-    uncomp_len = buf_in[4] | (buf_in[5] << 8) | (buf_in[6] << 16) | (buf_in[7] << 24);
+    uncomp_len = (buf_in[4] & 0xff) | ((buf_in[5] & 0xff) << 8) | ((buf_in[6] & 0xff) << 16) | ((buf_in[7] & 0xff) << 24);
 
     printf("Compressed size: %d Uncompressed size: %d\n", comp_len-4, uncomp_len-4);
 
@@ -78,16 +78,19 @@
 
     for (i = 0; i < comp_len-8;)
     {
-        int ret, len = read(fd_in, &buf_in, 1024);
+        int ret, len = 0;
+        if (zstream.avail_in == 0) {
+            len = read(fd_in, &buf_in, sizeof(buf_in));
 
-        dbgprintf("read %d bytes\n", len);
+            dbgprintf("read %d bytes\n", len);
 
-        last_out = zstream.total_out;
-
-        zstream.next_in = &buf_in[0];
-        zstream.avail_in = len;
+            zstream.next_in = &buf_in[0];
+            zstream.avail_in = len;
+        }
         zstream.next_out = &buf_out[0];
-        zstream.avail_out = 65536;
+        zstream.avail_out = sizeof(buf_out);
+
+        last_out = zstream.total_out;
 
         ret = inflate(&zstream, Z_SYNC_FLUSH);
         if (ret != Z_STREAM_END && ret != Z_OK)
@@ -103,7 +106,7 @@
 
         write(fd_out, &buf_out, zstream.total_out-last_out);
 
-        i += len;
+        i += (len - zstream.avail_in);
 
         if (ret == Z_STREAM_END || ret == Z_BUF_ERROR)
             break;
