rs02-fix.c 24.9 KB
Newer Older
1
/*  dvdisaster: Additional error correction for optical media.
2
 *  Copyright (C) 2004-2017 Carsten Gnoerlich.
3
 *
4 5 6 7 8 9
 *  Email: carsten@dvdisaster.org  -or-  cgnoerlich@fsfe.org
 *  Project homepage: http://www.dvdisaster.org
 *
 *  This file is part of dvdisaster.
 *
 *  dvdisaster is free software: you can redistribute it and/or modify
10
 *  it under the terms of the GNU General Public License as published by
11
 *  the Free Software Foundation, either version 3 of the License, or
12 13
 *  (at your option) any later version.
 *
14
 *  dvdisaster is distributed in the hope that it will be useful,
15 16 17 18 19
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
20
 *  along with dvdisaster. If not, see <http://www.gnu.org/licenses/>.
21 22 23 24 25 26 27 28 29 30 31 32
 */

#include "dvdisaster.h"

#include "rs02-includes.h"
#include "galois-inlines.h"

/***
 *** Internal housekeeping
 ***/

typedef struct
33 34 35
{  Image *image;
   EccHeader *eh;
   RS02Widgets *wl;
36 37 38 39 40 41 42 43 44 45 46 47
   RS02Layout *lay;
   GaloisTables *gt;
   ReedSolomonTables *rt;
   int earlyTermination;
   char *msg;
   unsigned char *imgBlock[255];
} fix_closure;

static void fix_cleanup(gpointer data)
{  fix_closure *fc = (fix_closure*)data;
   int i;

48
   UnregisterCleanup();
49 50 51 52 53 54 55 56 57 58 59 60

   if(Closure->guiMode)
   {  if(fc->earlyTermination)
         SwitchAndSetFootline(fc->wl->fixNotebook, 1,
			      fc->wl->fixFootline,
			      _("<span %s>Aborted by unrecoverable error.</span>"),
			      Closure->redMarkup); 
      AllowActions(TRUE);
   }

   /** Clean up */

61
   if(fc->image) CloseImage(fc->image);
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
   if(fc->msg) g_free(fc->msg);

   for(i=0; i<255; i++)
   {  if(fc->imgBlock[i])
	 g_free(fc->imgBlock[i]); 
   }

   if(fc->lay) g_free(fc->lay);

   if(fc->gt) FreeGaloisTables(fc->gt);
   if(fc->rt) FreeReedSolomonTables(fc->rt);

   g_free(fc);

   if(Closure->guiMode)
     g_thread_exit(0);
}

/*
 * Expand a truncated image 
 */

84 85 86
static void expand_image(fix_closure *fc, gint64 new_size)
{  Image *image = fc->image;
   int last_percent, percent;
87 88
   gint64 sectors, new_sectors;

89
   if(!LargeSeek(image->file, image->file->size))
90 91 92
     Stop(_("Failed seeking to end of image: %s\n"), strerror(errno));

   last_percent = 0;
93
   new_sectors = new_size - image->sectorSize;
94 95 96 97
   for(sectors = 0; sectors < new_sectors; sectors++)
   {  unsigned char buf[2048];
      int n;

98 99
      CreateMissingSector(buf, image->sectorSize+sectors, 
			  fc->eh->mediumFP, FINGERPRINT_SECTOR, 
100
			  "RS02 fix placeholder");
101
      n = LargeWrite(image->file, buf, 2048);
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
      if(n != 2048)
	Stop(_("Failed expanding the image: %s\n"), strerror(errno));

      percent = (100*sectors) / new_sectors;
      if(last_percent != percent)
      {  if(Closure->guiMode)
	  ;
	 else PrintProgress(_("Expanding image: %3d%%"), percent);
	 last_percent = percent; 
      }
   }

   if(Closure->guiMode)
     ;
   else 
   {  PrintProgress(_("Expanding image: %3d%%"), 100);
      PrintProgress("\n");
   }
120 121 122

   image->sectorSize = new_size;
   image->file->size = new_size;
123 124 125 126 127 128
}

/***
 *** Test and fix the current image.
 ***/

129 130 131
void RS02Fix(Image *image)
{  Method *self = FindMethod("RS02");
   RS02Widgets *wl = (RS02Widgets*)self->widgetList;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
   RS02Layout *lay;
   fix_closure *fc = g_malloc0(sizeof(fix_closure)); 
   EccHeader *eh;
#ifdef HAVE_BIG_ENDIAN
   EccHeader *eh_swapped;
#endif
   gint32 *gf_index_of;
   gint32 *gf_alpha_to;
   gint64 block_idx[255];
   gint64 s;
   guint32 crc_buf[512];
   gint64 crc_sector_byte;
   int nroots,ndata;
   int crc_idx, ecc_idx;
   int crc_valid = TRUE;
   int cache_size, cache_sector, cache_offset;
   int erasure_count,erasure_list[255],erasure_map[255];
   int error_count;
   int percent, last_percent;
   int worst_ecc = 0, local_plot_max = 0;
   int i,j;
   gint64 crc_errors=0;
   gint64 data_count=0;
   gint64 ecc_count=0;
   gint64 crc_count=0;
   gint64 data_corr=0;
   gint64 ecc_corr=0;
   gint64 corrected=0;
   gint64 uncorrected=0;
   gint64 damaged_sectors=0;
   gint64 damaged_eccblocks=0;
   gint64 damaged_eccsecs=0;
   gint64 expected_sectors;
165
   char *t=NULL;
166 167 168

   /*** Register the cleanup procedure for GUI mode */

169
   fc->image = image;
170 171 172 173 174 175 176 177 178 179 180
   fc->wl = wl;
   fc->earlyTermination = TRUE;
   RegisterCleanup(_("Repairing of image aborted"), fix_cleanup, fc);

   /*** Open the image file */

   if(Closure->guiMode)
     SetLabelText(GTK_LABEL(wl->fixHeadline),
		  _("<big>Repairing the image.</big>\n<i>%s</i>"),
		  _("Opening files..."));

181 182
   eh  = fc->eh  = image->eccHeader;
   lay = fc->lay = RS02LayoutFromImage(image); 
183 184 185 186 187 188 189 190 191 192 193 194 195 196

   ndata  = lay->ndata;
   nroots = lay->nroots;

   /*** Set up the Galois field arithmetic */

   fc->gt      = CreateGaloisTables(RS_GENERATOR_POLY);
   fc->rt      = CreateReedSolomonTables(fc->gt, RS_FIRST_ROOT, RS_PRIM_ELEM, nroots);
   gf_index_of = fc->gt->indexOf;
   gf_alpha_to = fc->gt->alphaTo;

   /*** Expand a truncated image with "dead sector" markers */

   expected_sectors = lay->eccSectors+lay->dataSectors;
197 198
   if(image->sectorSize < expected_sectors)
     expand_image(fc, expected_sectors);
199 200 201 202

   /*** Announce what we going to do */

   if(Closure->guiMode)
203 204 205 206 207
   {  char *msg = g_strdup_printf(_("Image contains error correction data: Method RS02, %d roots, %4.1f%% redundancy."),
				  eh->eccBytes, 
				  ((double)eh->eccBytes*100.0)/(double)eh->dataBytes);

      SetLabelText(GTK_LABEL(wl->fixHeadline),
208 209 210 211 212
		  _("<big>Repairing the image.</big>\n<i>%s</i>"), msg);
      RS02SetFixMaxValues(wl, eh->dataBytes, eh->eccBytes, expected_sectors);
      g_free(msg);
   }    

213 214
   PrintLog(_("\nFix mode(%s): Repairable sectors will be fixed in the image.\n"),
	    "RS02");
215 216 217

   /*** Truncate an image with trailing garbage */

218 219
   if(image->sectorSize > expected_sectors)
   { gint64 diff = image->sectorSize - expected_sectors;
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
     char *trans = _("The image file is %lld sectors longer as noted in the\n"
		     "ecc data. This might simply be zero padding, but could\n"
		     "also mean that the image was manipulated after appending\n"
		     "the error correction information.\n\n%s");

     if(diff>0 && diff<=2)
     {  int answer = ModalWarning(GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, NULL,
				  _("Image file is %lld sectors longer than expected.\n"
				    "Assuming this is a TAO mode medium.\n"
				    "%lld sectors will be removed from the image end.\n"),
				  diff, diff);

        if(!answer)
        {  SwitchAndSetFootline(fc->wl->fixNotebook, 1,
				fc->wl->fixFootline,
				_("<span %s>Aborted by user request!</span>"),
				Closure->redMarkup); 
	   fc->earlyTermination = FALSE;  /* suppress respective error message */
	   goto terminate;
	}

241
        if(!TruncateImage(image, (gint64)(2048*expected_sectors)))
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
	  Stop(_("Could not truncate %s: %s\n"),Closure->imageName,strerror(errno));
     }
     
     if(diff>2 && Closure->guiMode)
     {  int answer = ModalDialog(GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, NULL,
				 trans,
				 diff, 
				 _("Is it okay to remove the superfluous sectors?"));

       if(!answer)
       {  SwitchAndSetFootline(fc->wl->fixNotebook, 1,
			       fc->wl->fixFootline,
			       _("<span %s>Aborted by user request!</span>"),
			       Closure->redMarkup); 
	  fc->earlyTermination = FALSE;  /* suppress respective error message */
	  goto terminate;
       }

260
       if(!TruncateImage(image, (gint64)(2048*expected_sectors)))
261 262 263 264 265 266 267 268 269 270 271 272
	 Stop(_("Could not truncate %s: %s\n"),Closure->imageName,strerror(errno));

       PrintLog(_("Image has been truncated by %lld sectors.\n"), diff);
     }

     if(diff>2 && !Closure->guiMode)
     {  if(!Closure->truncate)
	   Stop(trans, 
		diff,
		_("Add the --truncate option to the program call\n"
		  "to have the superfluous sectors removed."));

273
	 if(!TruncateImage(image, (gint64)(2048*expected_sectors)))
274 275 276 277 278 279 280 281 282 283 284 285
	   Stop(_("Could not truncate %s: %s\n"),Closure->imageName,strerror(errno));

	 PrintLog(_("Image has been truncated by %lld sectors.\n"), diff);
     }
   }

   /*** Rewrite all headers from the one which was given us as a reference */

#ifdef HAVE_BIG_ENDIAN
   eh_swapped = g_malloc(sizeof(EccHeader));
   memcpy(eh_swapped, eh, sizeof(EccHeader));
   SwapEccHeaderBytes(eh_swapped);
286
   WriteRS02Headers(image->file, lay, eh_swapped);
287 288
   g_free(eh_swapped);
#else
289
   WriteRS02Headers(image->file, lay, eh);
290 291 292 293 294 295 296 297 298 299 300
#endif

   /*** Prepare buffers for ecc code processing.
	The first lay->protecedSectors are protected by ecc information.
	The medium is logically divided into ndata layers and nroots slices.
	Taking one sector from each layer and slice produces on ecc block
	on which the error correction is carried out. 
	There is a total of lay->sectorsPerLayer ecc blocks.
	A portion of cache_size sectors is read ahead from each layer/slice,
	giving a total cache size of 255*cache_size. */

301
   cache_size = 2*Closure->cacheMiB;  /* ndata+nroots=255 medium sectors are approx. 0.5MiB */
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

   for(i=0; i<255; i++)
      fc->imgBlock[i] = g_malloc(cache_size*2048);

   /*** Setup the block counters for mapping medium sectors to ecc blocks.
        Error correction begins at lay->CrcLayerIndex so that we have a chance
        of repairing the CRC information before we need it. */

   for(s=0, i=0; i<lay->ndata; s+=lay->sectorsPerLayer, i++)
     block_idx[i] = s + lay->firstCrcLayerIndex;

   ecc_idx = lay->firstCrcLayerIndex;

   cache_sector = cache_size;  /* forces instant reload of imgBlock cache */
   cache_offset = 2048*cache_sector;

   /*** CRCs for the first ecc block are taken from the ecc header.
	Preset pointers accordingly. */

   crc_sector_byte = 2048 *(lay->dataSectors + 2);  /* first sector with CRC info */
   crc_idx = 0;
   memcpy(crc_buf, (char*)eh + 2048, sizeof(guint32) * lay->ndata);

   /*** Test ecc blocks and attempt error correction */

   last_percent = -1;

   for(s=0; s<lay->sectorsPerLayer; s++)
   { gint64 si = (s + lay->firstCrcLayerIndex) % lay->sectorsPerLayer;
     int bi;

     /* See if user hit the Stop button */

     if(Closure->stopActions) 
336 337 338 339 340
     {   if(Closure->stopActions == STOP_CURRENT_ACTION) /* suppress memleak warning when closing window */
	   SwitchAndSetFootline(fc->wl->fixNotebook, 1,
				fc->wl->fixFootline,
				_("<span %s>Aborted by user request!</span>"),
				Closure->redMarkup); 
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
         fc->earlyTermination = FALSE;  /* suppress respective error message */
	 goto terminate;
     }

     /* Make sure to wrap the block_idx[] ptr properly */

     if(!si)
     {  gint64 bs;

        for(bs=0, i=0; i<lay->ndata; bs+=lay->sectorsPerLayer, i++)
	  block_idx[i] = bs;

	ecc_idx = 0;
     }

     if(s == 1) /* force CRC reload */
       crc_idx = 512;

     /* Fill cache with the next batch of cache_size ecc blocks. */

     if(cache_sector >= cache_size)
     {  
        if(lay->sectorsPerLayer-si < cache_size)
           cache_size = lay->sectorsPerLayer-si;

        for(i=0; i<ndata; i++)       /* Read data portion */
        {  int offset = 0;
	   for(j=0; j<cache_size; j++) 
369
	   {  RS02ReadSector(image, lay, fc->imgBlock[i]+offset, block_idx[i]+j);
370 371 372 373 374 375 376 377 378
	      offset += 2048;
	   }
	}

        for(i=0; i<nroots; i++)      /* and ecc portion */
        {  int offset = 0;
	   for(j=0; j<cache_size; j++) 
	   {  gint64 esi = RS02EccSectorIndex(lay, i, ecc_idx+j);

379
	      if(!LargeSeek(image->file, 2048*esi))
380 381
		Stop(_("Failed seeking to sector %lld in image: %s"), esi, strerror(errno));

382
	      if(LargeRead(image->file, fc->imgBlock[i+ndata]+offset, 2048) != 2048)
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
		Stop(_("Failed reading sector %lld in image: %s"), esi, strerror(errno));

	      offset += 2048;
	   }
	}

        cache_sector = cache_offset = 0;
     }

     /* Look for erasures based on the "dead sector" marker and CRC sums */

     erasure_count = error_count = 0;

     for(i=0; i<lay->ndata; i++)  /* Check the data sectors */
     {  
        erasure_map[i] = 0;
        if(block_idx[i] < lay->protectedSectors)  /* ignore the padding sectors! */
	{  int err = CheckForMissingSector(fc->imgBlock[i]+cache_offset, block_idx[i],
					   eh->mediumFP, eh->fpSector);
	   if(err != SECTOR_PRESENT)
	   {  erasure_map[i] = 1;
	      erasure_list[erasure_count++] = i;
	      damaged_sectors++;
	   }

	  if(block_idx[i] < lay->dataSectors)     /* only data sectors have CRCs */
	  {  guint32 crc = Crc32(fc->imgBlock[i]+cache_offset, 2048);
	     int err;

	     if(crc_idx >= 512)
413
	     {  if(!LargeSeek(image->file, crc_sector_byte))
414 415
		  Stop(_("Failed seeking in crc area: %s"), strerror(errno));
	
416
		if(LargeRead(image->file, crc_buf, 2048) != 2048)
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
		  Stop(_("problem reading crc data: %s"), strerror(errno));

		err = CheckForMissingSector((unsigned char*)crc_buf, crc_sector_byte/2048,
					    eh->mediumFP, eh->fpSector);

		crc_sector_byte += 2048;
		crc_idx = 0;
		crc_valid = (err == SECTOR_PRESENT);
	     }

	     if(crc_valid && !erasure_map[i] && crc != crc_buf[crc_idx])
	     {  erasure_map[i] = 3;
	        erasure_list[erasure_count++] = i;
	        PrintCLI(_("CRC error in sector %lld\n"),block_idx[i]);
		damaged_sectors++;
		crc_errors++;
	     }

	     data_count++;
	     crc_idx++;
          }
	  else if(block_idx[i] >= lay->dataSectors + 2) crc_count++;
	}
     }

     for(i=lay->ndata; i<GF_FIELDMAX; i++)  /* Check the ecc sectors */
443 444 445
     {  gint64 ecc_sector = RS02EccSectorIndex(lay, i-ndata, ecc_idx);
	int err = CheckForMissingSector(fc->imgBlock[i]+cache_offset,
					ecc_sector,
446
					eh->mediumFP, eh->fpSector);
447
	 
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
	if(err)
	{  erasure_map[i] = 1;
	   erasure_list[erasure_count++] = i;
	   damaged_sectors++;
	}
        else erasure_map[i] = 0;

	ecc_count++;
     }

     /* Trivially reject uncorrectable ecc block */

     if(erasure_count>lay->nroots)   /* uncorrectable */
     {  if(!Closure->guiMode)
	{  PrintCLI(_("* Ecc block %lld: %3d unrepairable sectors: "), s, erasure_count);

	   for(i=0; i<erasure_count; i++)
	   {  gint64 loc = erasure_list[i];
466 467 468 469

	      if(loc < ndata) PrintCLI("%lld ", block_idx[loc]);
	      else            PrintCLI("%lld ", RS02EccSectorIndex(lay, loc-ndata, ecc_idx));

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
	   }
	   PrintCLI("\n");
	}

	uncorrected += erasure_count;
	goto skip;
     }

     /* Build ecc block and attempt to correct it */

     for(bi=0; bi<2048; bi++)  /* Run through each ecc block byte */
     {  int offset = cache_offset+bi;
        int r, deg_lambda, el, deg_omega;
	int u,q,tmp,num1,num2,den,discr_r;
	int lambda[nroots+1], syn[nroots]; /* Err+Eras Locator poly * and syndrome poly */
	int b[nroots+1], t[nroots+1], omega[nroots+1];
	int root[nroots], reg[nroots+1], loc[nroots];
	int syn_error, count;
	int k;

	/* Form the syndromes; i.e., evaluate data(x) at roots of g(x) */

	for(i=0; i<nroots; i++)
	  syn[i] = fc->imgBlock[0][offset];

	for(j=1; j<GF_FIELDMAX; j++)
	{  int data = fc->imgBlock[j][offset];

	   for(i=0;i<nroots;i++)
	   {  if(syn[i] == 0) syn[i] = data;
	      else syn[i] = data ^ gf_alpha_to[mod_fieldmax(gf_index_of[syn[i]] + (RS_FIRST_ROOT+i)*RS_PRIM_ELEM)];
	   }
	}

	/* Convert syndromes to index form, check for nonzero condition */

	syn_error = 0;
	for(i=0; i<nroots; i++)
	{  syn_error |= syn[i];
	   syn[i] = gf_index_of[syn[i]];
	}

	/* If it is already correct by coincidence, we have nothing to do any further */

	if(syn_error) damaged_eccblocks++; 
	else continue;

//printf("Syndrome error for ecc block %lld, byte %d\n",s,bi);

	/* If we have found any erasures, 
	   initialize lambda to be the erasure locator polynomial */

	memset(lambda+1, 0, nroots*sizeof(lambda[0]));
	lambda[0] = 1;

	if(erasure_count > 0)
	{  lambda[1] = gf_alpha_to[mod_fieldmax(RS_PRIM_ELEM*(GF_FIELDMAX-1-erasure_list[0]))];
	   for(i=1; i<erasure_count; i++) 
	   {  u = mod_fieldmax(RS_PRIM_ELEM*(GF_FIELDMAX-1-erasure_list[i]));
	      for(j=i+1; j>0; j--) 
	      {  tmp = gf_index_of[lambda[j-1]];
	         if(tmp != GF_ALPHA0)
		   lambda[j] ^= gf_alpha_to[mod_fieldmax(u + tmp)];
	      }
	   }
	}	

	for(i=0; i<nroots+1; i++)
	  b[i] = gf_index_of[lambda[i]];
  
	/* Begin Berlekamp-Massey algorithm to determine error+erasure locator polynomial */

	r = erasure_count;   /* r is the step number */
	el = erasure_count;
	while(++r <= nroots) /* Compute discrepancy at the r-th step in poly-form */
	{  
	  discr_r = 0;
	  for(i=0; i<r; i++)
	    if((lambda[i] != 0) && (syn[r-i-1] != GF_ALPHA0))
	      discr_r ^= gf_alpha_to[mod_fieldmax(gf_index_of[lambda[i]] + syn[r-i-1])];

	  discr_r = gf_index_of[discr_r];	/* Index form */

	  if(discr_r == GF_ALPHA0) 
	  {  /* B(x) = x*B(x) */
	    memmove(b+1, b, nroots*sizeof(b[0]));
	    b[0] = GF_ALPHA0;
	  } 
	  else 
	  {  /* T(x) = lambda(x) - discr_r*x*b(x) */
	     t[0] = lambda[0];
	     for(i=0; i<nroots; i++) 
	     {  if(b[i] != GF_ALPHA0)
		     t[i+1] = lambda[i+1] ^ gf_alpha_to[mod_fieldmax(discr_r + b[i])];
	        else t[i+1] = lambda[i+1];
	     }

	     if(2*el <= r+erasure_count-1) 
	     {  el = r + erasure_count - el;

	        /* B(x) <-- inv(discr_r) * lambda(x) */
	        for(i=0; i<=nroots; i++)
		  b[i] = (lambda[i] == 0) ? GF_ALPHA0 : mod_fieldmax(gf_index_of[lambda[i]] - discr_r + GF_FIELDMAX);
	     } 
	     else 
	     {  /* 2 lines below: B(x) <-- x*B(x) */
	        memmove(b+1, b, nroots*sizeof(b[0]));
		b[0] = GF_ALPHA0;
	     }

	     memcpy(lambda,t,(nroots+1)*sizeof(t[0]));
	  }
	}

	/* Convert lambda to index form and compute deg(lambda(x)) */
	deg_lambda = 0;
	for(i=0; i<nroots+1; i++)
	{  lambda[i] = gf_index_of[lambda[i]];
	   if(lambda[i] != GF_ALPHA0)
	     deg_lambda = i;
	}

	/* Find roots of the error+erasure locator polynomial by Chien search */
	memcpy(reg+1, lambda+1, nroots*sizeof(reg[0]));
	count = 0;		/* Number of roots of lambda(x) */

	for(i=1, k=RS_PRIMTH_ROOT-1; i<=GF_FIELDMAX; i++, k=mod_fieldmax(k+RS_PRIMTH_ROOT))
	{  q=1; /* lambda[0] is always 0 */

	   for(j=deg_lambda; j>0; j--)
	   {  if(reg[j] != GF_ALPHA0) 
	      {  reg[j] = mod_fieldmax(reg[j] + j);
		 q ^= gf_alpha_to[reg[j]];
	      }
	   }

	   if(q != 0) continue; /* Not a root */

	   /* store root (index-form) and error location number */

	   root[count] = i;
	   loc[count] = k;

	   /* If we've already found max possible roots, abort the search to save time */

	   if(++count == deg_lambda) break;
	}

	/* deg(lambda) unequal to number of roots => uncorrectable error detected */

	if(deg_lambda != count)
	{  PrintLog("Decoder problem (%d != %d) for %d sectors: ", deg_lambda, count, erasure_count);

	   for(i=0; i<erasure_count; i++)
	   {  gint64 loc = erasure_list[i];
625 626 627

	     if(loc < ndata) PrintLog("%lld ", block_idx[loc]);
	     else            PrintLog("%lld ", RS02EccSectorIndex(lay, loc-ndata, ecc_idx));
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
	   }
	   PrintLog("\n");
	   uncorrected += erasure_count;
	   goto skip;
	}

	/* Compute err+eras evaluator poly omega(x) = syn(x)*lambda(x) 
	   (modulo x**nroots). in index form. Also find deg(omega). */

	deg_omega = deg_lambda-1;

	for(i=0; i<=deg_omega; i++)
	{  tmp = 0;
	   for(j=i; j>=0; j--)
	   {  if((syn[i - j] != GF_ALPHA0) && (lambda[j] != GF_ALPHA0))
	        tmp ^= gf_alpha_to[mod_fieldmax(syn[i - j] + lambda[j])];
	   }

	   omega[i] = gf_index_of[tmp];
	}

	/* Compute error values in poly-form. 
	   num1 = omega(inv(X(l))), 
	   num2 = inv(X(l))**(FIRST_ROOT-1) and 
	   den  = lambda_pr(inv(X(l))) all in poly-form. */

	for(j=count-1; j>=0; j--)
	{  num1 = 0;

	   for(i=deg_omega; i>=0; i--) 
	   {  if(omega[i] != GF_ALPHA0)
	         num1 ^= gf_alpha_to[mod_fieldmax(omega[i] + i * root[j])];
	   }

	   num2 = gf_alpha_to[mod_fieldmax(root[j] * (RS_FIRST_ROOT - 1) + GF_FIELDMAX)];
	   den = 0;
    
	   /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */

	   for(i=MIN(deg_lambda, nroots-1) & ~1; i>=0; i-=2) 
	   {  if(lambda[i+1] != GF_ALPHA0)
	        den ^= gf_alpha_to[mod_fieldmax(lambda[i+1] + i * root[j])];
	   }

	   /* Apply error to data */

	   if(num1 != 0)
	   {  int location = loc[j];
		
	      if(erasure_map[location] != 1)  /* erasure came from CRC error */
	      {  int old = fc->imgBlock[location][offset];
		 int new = old ^ gf_alpha_to[mod_fieldmax(gf_index_of[num1] + gf_index_of[num2] + GF_FIELDMAX - gf_index_of[den])];
		 char *msg;
		 gint64 sector;

		 if(erasure_map[location] == 3)  /* erasure came from CRC error */
		 {  msg = _("-> CRC-predicted error in sector %lld at byte %4d (value %02x '%c', expected %02x '%c')\n");
		 }
		 else
		 {  msg = _("-> Non-predicted error in sector %lld at byte %4d (value %02x '%c', expected %02x '%c')\n");
		    if(erasure_map[location] == 0) /* remember error location */
		    {  erasure_map[location] = 7;
		       error_count++;  
		    }
		 }

		 if(location < ndata)
		      sector = block_idx[location];
696
		 else sector = RS02EccSectorIndex(lay, location-ndata, ecc_idx);
697 698 699 700 701 702 703 704 705 706 707 708

		 PrintCLI(msg,
			  sector, bi, 
			  old, isprint(old) ? old : '.',
			  new, isprint(new) ? new : '.');
	      }

	      fc->imgBlock[location][offset] ^= gf_alpha_to[mod_fieldmax(gf_index_of[num1] + gf_index_of[num2] + GF_FIELDMAX - gf_index_of[den])];
	   }
	}
     }

709
     /* Write corrected sectors back to disk
710 711 712 713 714 715 716 717 718 719
        and report them */

     erasure_count += error_count;  /* total errors encountered */

     if(erasure_count)
     {  PrintCLI(_("  %3d repaired sectors: "), erasure_count);

        for(i=0; i<255; i++)
        {  gint64 sec;
           char type='?';
720
	   int n;
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
	   
	   if(!erasure_map[i]) continue;

	   switch(erasure_map[i])
	   {  case 1:  /* dead sector */
	        type = 'd';
	        break;

	      case 3:  /* crc error */
	        type = 'c';
	        break;

	      case 7:  /* other (new) error */
		type = 'n';
		damaged_sectors++;
	        break;
	   }

	   if(i < ndata) {  data_corr++; sec = block_idx[i]; }
740 741
	   else          {  ecc_corr++;  sec = RS02EccSectorIndex(lay, i-ndata, ecc_idx); }

742 743 744 745 746 747
	   corrected++;

	   PrintCLI("%lld%c ", sec, type);

	   /* Write the recovered sector */

748
	   if(!LargeSeek(image->file, (gint64)(2048*sec)))
749 750 751
	     Stop(_("Failed seeking to sector %lld in image [%s]: %s"),
		  sec, "FW", strerror(errno));

752 753 754 755 756
	   /* augmented images can not have sizes not a multiple of 2048,
	      e.g. we need not to examine the ->inLast value. */
	   
	   n = LargeWrite(image->file, cache_offset+fc->imgBlock[i], 2048);
	   if(n != 2048)
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	     Stop(_("could not write medium sector %lld:\n%s"), sec, strerror(errno));

	}

	PrintCLI("\n");
     }

skip:
     /* Collect some damage statistics */
     
     if(erasure_count)
       damaged_eccsecs++;

     if(erasure_count>worst_ecc)
       worst_ecc = erasure_count;

     if(erasure_count>local_plot_max)
       local_plot_max = erasure_count;

     /* Advance the cache pointers */

     cache_sector++;
     cache_offset += 2048;

     /* Report progress */

     percent = (1000*s)/lay->sectorsPerLayer;

     if(last_percent != percent) 
     {  if(Closure->guiMode)
	{  
	   RS02AddFixValues(wl, percent, local_plot_max);
	   local_plot_max = 0;

	   //if(last_corrected != corrected || last_uncorrected != uncorrected) 
	   RS02UpdateFixResults(wl, corrected, uncorrected);
	}
        else PrintProgress(_("Ecc progress: %3d.%1d%%"),percent/10,percent%10);
        last_percent = percent;
     }

     /* Increment the block indices */

     for(i=0; i<lay->ndata; i++)
	block_idx[i]++;

     ecc_idx++;
   }

   /*** Print results */

   PrintProgress(_("Ecc progress: 100.0%%\n"));

   if(corrected > 0) PrintLog(_("Repaired sectors: %lld (%lld data, %lld ecc)\n"),
			      corrected, data_corr, ecc_corr);
   if(uncorrected > 0) 
   {  PrintLog(_("Unrepaired sectors: %lld\n"), uncorrected);      
      if(Closure->guiMode)
        SwitchAndSetFootline(wl->fixNotebook, 1, wl->fixFootline,
			     _("Image sectors could not be fully restored "
			       "(%lld repaired; <span %s>%lld unrepaired</span>)"),
			     corrected, Closure->redMarkup, uncorrected);
   }
   else
   {  if(!corrected)
      {    t=_("Good! All sectors are already present.");
           PrintLog("%s\n", t);
      }
      else 
      {    t=_("Good! All sectors are repaired.");
	   PrintLog("%s\n", t);
      }
   }
   if(corrected > 0 || uncorrected > 0)
     PrintLog(_("Erasure counts per ecc block:  avg =  %.1f; worst = %d.\n"),
	     (double)damaged_sectors/(double)damaged_eccsecs,worst_ecc);

   if(Closure->guiMode && t)
     SwitchAndSetFootline(wl->fixNotebook, 1, wl->fixFootline,
			  "%s %s", _("Repair results:"), t);

   Verbose("\nSummary of processed sectors:\n");
   Verbose("%lld damaged sectors\n", damaged_sectors);
   Verbose("%lld CRC errors\n", crc_errors);
   Verbose("%lld of %lld ecc blocks damaged (%lld / %lld sectors)\n",
	   damaged_eccblocks, 2048*lay->sectorsPerLayer,
	   damaged_eccsecs, lay->sectorsPerLayer);
   if(data_count != lay->dataSectors)
        g_printf("ONLY %lld of %lld data sectors processed\n", 
		 (long long int)data_count, (long long int)lay->dataSectors);
   else Verbose("all data sectors processed\n");

   if(crc_count != lay->crcSectors)
        g_printf("%lld of %lld crc sectors processed\n", 
		 (long long int)crc_count, (long long int)lay->crcSectors);
   else Verbose("all  crc sectors processed\n");

   if(ecc_count != lay->rsSectors)
        g_printf("%lld of %lld ecc sectors processed\n", 
		 (long long int)ecc_count, (long long int)lay->rsSectors);
   else Verbose("all  ecc sectors processed\n");

   /*** Clean up */

   fc->earlyTermination = FALSE;

terminate:
   fix_cleanup((gpointer)fc);
}