diff --git a/nand-image-builder.c b/nand-image-builder.c
index d8c548f6a071a35f919adc42d71ebd1cc1c56c9c..d0e05b278e84d1982c9bde2ec623977288082a58 100644
--- a/nand-image-builder.c
+++ b/nand-image-builder.c
@@ -87,7 +87,7 @@ int main(int argc, char **argv)
     uint8_t *page_buffer;
     uint32_t countMask, count = 0;
     uint32_t numBytesRead, totalBytesRead = 0;
-    uint32_t sector_sz, oob_sz, oob_ecc_len, oob_ecc_ofs = 0;
+    uint32_t sector_sz, oob_sz, oob_ecc_sz, oob_ecc_len, oob_ecc_ofs = 0;
     int pages_in_block, i, j = 0;
     const char *input_file = NULL;
     const char *output_file = NULL;
@@ -225,13 +225,22 @@ int main(int argc, char **argv)
     /* Number of ecc_code bytes, v = ceil(p/8) = ceil(m*t/8) = p_partial_page_size+s-u */
     oob_ecc_len = (sector_sz + oob_sz) - data_bytes;
 
+    if        (ecc_level == 4) {
+        oob_ecc_sz = 16;
+    } else if (ecc_level == 8) {
+        oob_ecc_sz = 27;
+    } else {
+        printf("Unsupported ecc level %d\n", ecc_level);
+        goto exit;
+    }
+        
     if (oob_ecc_len > oob_sz)
     {
         printf(" Number of spare bytes must be at least %d\n", oob_ecc_len);
         goto exit;
     }
 
-    oob_ecc_ofs = oob_sz - oob_ecc_len;
+    oob_ecc_ofs = oob_ecc_sz - oob_ecc_len;
 
     countMask = pages_in_block - 1;
 
@@ -275,6 +284,7 @@ int main(int argc, char **argv)
     printf("OOB size per subpage %d\n", oob_sz);
     printf("OOB_ECC_LEN %d\n", oob_ecc_len);
     printf("OOB_ECC_OFS %d\n", oob_ecc_ofs);
+    printf("OOB_ECC_SIZE %d\n", oob_ecc_sz);
 
     while (!feof(in_file))
 
@@ -284,7 +294,7 @@ int main(int argc, char **argv)
 
         numBytesRead = fread(page_buffer, (size_t)1, (sector_sz)*SECTORS_PER_PAGE, in_file);
         totalBytesRead += numBytesRead;
-
+	printf("Fread %d\n", totalBytesRead);
         if (numBytesRead == 0)
         {
             printf("Fread failed or file size is zero\r\n");
@@ -310,11 +320,13 @@ int main(int argc, char **argv)
         for (i = 0; i != SECTORS_PER_PAGE; ++i)
         {
             const uint8_t *sector_data = page_buffer + sector_sz * i;
-            uint8_t *sector_oob = page_buffer + sector_sz * SECTORS_PER_PAGE + oob_sz * i;
+            uint8_t *sector_oob = page_buffer + sector_sz * SECTORS_PER_PAGE + oob_ecc_sz * i;
+           	printf("offset %d\n", sector_sz * SECTORS_PER_PAGE + oob_ecc_sz * i);
+
             if (erase_block)
             {
-                // Erased page ECC consumes full 7 bytes, including high 4 bits set to 0xf
-                memset(sector_oob + oob_ecc_ofs, 0xff, oob_ecc_len);
+                // Erased page ECC consumes oob_ecc_sz bytes
+                memset(sector_oob + oob_ecc_ofs, 0xff, oob_ecc_sz);
             }
             else
             {