diff --git a/coders/rgf.c b/coders/rgf.c
index ec124e4..6409762 100644
--- a/coders/rgf.c
+++ b/coders/rgf.c
@@ -357,8 +357,6 @@
     Convert MIFF to bit pixels.
   */
   (void) SetImageType(image,BilevelType,exception);
-  bit=0;
-  byte=0;
   x=0;
   y=0;
   for (y=0; y < (ssize_t) image->rows; y++)
@@ -366,6 +364,8 @@
     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
     if (p == (const Quantum *) NULL)
       break;
+    bit=0;
+    byte=0;
     for (x=0; x < (ssize_t) image->columns; x++)
     {
       byte>>=1;
@@ -377,12 +377,14 @@
           /*
             Write a bitmap byte to the image file.
           */
-	  (void) WriteBlobByte(image,byte);
+          (void) WriteBlobByte(image,byte);
           bit=0;
           byte=0;
         }
-        p+=GetPixelChannels(image);
-      }
+      p+=GetPixelChannels(image);
+    }
+    if (bit != 0)
+      (void) WriteBlobByte(image,byte);
     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
       image->rows);
     if (status == MagickFalse)