File: read-adaptive.c

package info (click to toggle)
dvdisaster 0.72.4-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 20,088 kB
  • ctags: 6,526
  • sloc: ansic: 29,301; php: 3,324; sh: 370; xml: 296; makefile: 73; cs: 33
file content (1726 lines) | stat: -rw-r--r-- 50,615 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
336
337
338
339
340
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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
413
414
415
416
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
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
625
626
627
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
/*  dvdisaster: Additional error correction for optical media.
 *  Copyright (C) 2004-2012 Carsten Gnoerlich.
 *  Project home page: http://www.dvdisaster.com
 *  Email: carsten@dvdisaster.com  -or-  cgnoerlich@fsfe.org
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  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
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA,
 *  or direct your browser at http://www.gnu.org.
 */

#include "dvdisaster.h"

#include "scsi-layer.h"
#include "udf.h"

#include "rs02-includes.h"

//#define CHECK_VISITED 1        /* This gives only reasonable output            */
                                 /* when the .ecc file is present while reading! */ 

/***
 *** Local data package used during reading
 ***/

enum { IMAGE_ONLY, ECC_IN_FILE, ECC_IN_IMAGE };

typedef struct
{  DeviceHandle *dh;            /* device we are reading from */
   gint64 sectors;              /* sectors in medium (maybe cooked value from file system) */
   LargeFile *image;            /* image file */
   int readMode;                /* see above enum for choices */
   EccInfo *ei;                 /* ecc info and header struct */
   EccHeader *eh;               /* if ecc information is present */
   int rs01LayerSectors;        /* length of each RS01 ecc layer in sectors */
   RS02Layout *lay;             /* layout of RS02 type ecc data */

   AlignedBuffer *ab;           /* buffer suitable for reading from the drive */
   unsigned char *buf;          /* buffer component from above */
   Bitmap *map;                 /* bitmap for keeping track of read sectors */
   CrcBuf *crcBuf;              /* preloaded CRC info from ecc data */

   unsigned char *fingerprint;  /* needed for missing sector */
   char *volumeLabel;           /* generation */

   gint64 readable;             /* current outcome of reading process */
   gint64 unreadable;
   gint64 correctable;

   gint64 firstSector;          /* user limited reading range */
   gint64 lastSector;

   gint64 *intervals;           /* queue for keeping track of unread intervals */
   gint64 maxIntervals;
   gint64 nIntervals;

   gint64 intervalStart;        /* information about currently processed interval */
   gint64 intervalEnd;
   gint64 intervalSize;
   gint64 highestWrittenSector; /* current size of image file */ 
 
   char progressMsg[256];       /* message output related */
   char progressBs[256];
   char progressSp[256];
   int  progressMsgLen;
   int  lastPercent;            /* used to determine next progress update */
   gint64 lastUnreadable;       /* used to find out whether something changed */
   gint64 lastCorrectable;      /* since last progress output */
   char *subtitle;              /* description of reading mode */
 
   int sectorsPerSegment;       /* number of sectors per spiral segment */
   int *segmentState;           /* tracks whether all sectors within segment are processed */

   int earlyTermination;        /* information about termination cause */

#ifdef CHECK_VISITED
   char *count;
#endif

} read_closure;

static void cleanup(gpointer data)
{  read_closure *rc = (read_closure*)data;

   Closure->cleanupProc = NULL;

   /* Reset temporary ignoring of fatal errors.
      User has to set this in the preferences to make it permanent. */

   if(Closure->ignoreFatalSense == 2)
      Closure->ignoreFatalSense = 0;

   /* Rewrite the header sectors if we were reading an RS02 image;
      otherwise the image will not be recognized later. */

   if(rc->readMode == ECC_IN_IMAGE)   
   {  RS02Layout *lay = rc->lay;
      guint64 hpos;
      guint64 end = lay->eccSectors+lay->dataSectors;

      if(rc->highestWrittenSector+1 < end)  /* image may have been partially read */
	end = rc->highestWrittenSector+1;

      /* Careful: we must not call Stop() here to avoid infinite
	 recursion in error situations. */

      if(lay->firstEccHeader > end)  /* ecc area not reached during read? */
	goto bail_out;

      if(!LargeSeek(rc->image, 2048*lay->firstEccHeader))
	goto bail_out;
   
      if(LargeWrite(rc->image, rc->eh, sizeof(EccHeader)) != sizeof(EccHeader))
	goto bail_out;

      hpos = (lay->protectedSectors + lay->headerModulo - 1) / lay->headerModulo;
      hpos *= lay->headerModulo;

      while(hpos < end)
      {  if(!LargeSeek(rc->image, 2048*hpos))
	  break;

	if(LargeWrite(rc->image, rc->eh, sizeof(EccHeader)) != sizeof(EccHeader))
	  break;

	hpos += lay->headerModulo;
      }
   }

bail_out:
   if(Closure->guiMode)
   {  if(rc->earlyTermination)
        SetAdaptiveReadFootline(_("Aborted by unrecoverable error."), Closure->redText);

      AllowActions(TRUE);
   }

   if(rc->image)   
     if(!LargeClose(rc->image))
       Stop(_("Error closing image file:\n%s"), strerror(errno));
   if(rc->dh)      CloseDevice(rc->dh);
 
   if(rc->ei) FreeEccInfo(rc->ei);

   if(rc->subtitle) g_free(rc->subtitle);
   if(rc->segmentState) g_free(rc->segmentState);

   if(rc->ab) FreeAlignedBuffer(rc->ab);
   
   if(rc->intervals) g_free(rc->intervals);
   if(rc->crcBuf) FreeCrcBuf(rc->crcBuf);

   if(rc->fingerprint) g_free(rc->fingerprint);
   if(rc->volumeLabel) g_free(rc->volumeLabel);

   if(rc->map)
     FreeBitmap(rc->map);

   g_free(rc);

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

/***
 *** Sorted queue of unread intervals
 ***/

/*
 * Sort new interval into the queue
 */

static void add_interval(read_closure *rc, gint64 start, gint64 size)
{  int i,si;
  
  /* Trivial case: empty interval list */

  if(rc->nIntervals == 0)
  {  rc->intervals[0] = start;
     rc->intervals[1] = size;
     rc->nIntervals++;
     return;
  }

  /* Find insertion place in list */

  for(i=0,si=0; i<rc->nIntervals; i++,si+=2)
    if(size > rc->intervals[si+1])
      break;

  /* Make sure we have enough space in the array */

  rc->nIntervals++;
  if(rc->nIntervals > rc->maxIntervals)
  {  rc->maxIntervals *= 2;
     
     rc->intervals = g_realloc(rc->intervals, rc->maxIntervals*2*sizeof(gint64));
  }


  /* Shift unless we insert at the list tail */

  if(i<rc->nIntervals-1)
    memmove(rc->intervals+si+2, rc->intervals+si, 2*sizeof(gint64)*(int)(rc->nIntervals-i-1));

  /* Add new pair into the list */
  
  rc->intervals[si]   = start;
  rc->intervals[si+1] = size;
}

/*
 * Remove first element from the queue
 */

static void pop_interval(read_closure *rc)
{  
  if(rc->nIntervals > 0)
  {  rc->nIntervals--;
     memmove(rc->intervals, rc->intervals+2, 2*sizeof(gint64)*(int)rc->nIntervals);
  }
}

/*
 * Print the queue (for debugging purposes only)
 */

void print_intervals(read_closure *rc)
{  int i;

   printf("%lld Intervals:\n", (long long int)rc->nIntervals);
   for(i=0; i<rc->nIntervals; i++)
     printf("%7lld [%7lld..%7lld]\n",
	    (long long int)rc->intervals[2*i+1], 
	    (long long int)rc->intervals[2*i], 
	    (long long int)rc->intervals[2*i]+rc->intervals[2*i+1]-1);
}

/***
 *** Convenience functions for printing the progress message
 ***/

static void print_progress(read_closure *rc, int immediate)
{  int n;
   int total = rc->readable+rc->correctable;
   int percent = (int)((1000LL*(long long)total)/rc->sectors);

   if(Closure->guiMode)
      return;

   if(   rc->lastPercent >= percent 
      && rc->lastCorrectable == rc->correctable
      && rc->lastUnreadable  == rc->unreadable
      && !immediate)
     return;

   rc->lastPercent = percent;
   rc->lastCorrectable = rc->correctable;
   rc->lastUnreadable  = rc->unreadable;

   if(rc->ei)
     n = g_snprintf(rc->progressMsg, 256,
		    _("Repairable: %2d.%1d%% (correctable: %lld; now reading [%lld..%lld], size %lld)"),
		    percent/10, percent%10, rc->correctable, 
		    rc->intervalStart, rc->intervalStart+rc->intervalSize-1, rc->intervalSize);
   else
     n = g_snprintf(rc->progressMsg, 256,
		    _("Repairable: %2d.%1d%% (missing: %lld; now reading [%lld..%lld], size %lld)"),
		    percent/10, percent%10, rc->sectors-rc->readable, 
		    rc->intervalStart, rc->intervalStart+rc->intervalSize-1, rc->intervalSize);

   if(n>255) n = 255;

   /* If the new message is shorter, overwrite old message with spaces */

   if(rc->progressMsgLen > n)
   {  rc->progressSp[rc->progressMsgLen] = 0;
      rc->progressBs[rc->progressMsgLen] = 0;
      PrintCLI("%s%s", rc->progressSp, rc->progressBs);
      rc->progressSp[rc->progressMsgLen] = ' ';
      rc->progressBs[rc->progressMsgLen] = '\b';
   }

   /* Write new message */

   rc->progressBs[n] = 0;
   PrintCLI("%s%s", rc->progressMsg, rc->progressBs);
   rc->progressBs[n] = '\b';



   rc->progressMsgLen = n;
}

static void clear_progress(read_closure *rc)
{
   if(!rc->progressMsgLen || Closure->guiMode)
     return;

   rc->progressSp[rc->progressMsgLen] = 0;
   PrintCLI("%s", rc->progressSp);
   rc->progressSp[rc->progressMsgLen] = ' ';

   rc->progressBs[rc->progressMsgLen] = 0;
   PrintCLI("%s", rc->progressBs);
   rc->progressBs[rc->progressMsgLen] = '\b';

   rc->progressMsgLen = 0;
}

/*
 * Sector markup in the spiral
 */

static void mark_sector(read_closure *rc, gint64 sector, GdkColor *color)
{  int segment;
   int changed = FALSE;

   if(!Closure->guiMode) return;

   segment = sector / rc->sectorsPerSegment;

   if(color)
   {  GdkColor *old = Closure->readAdaptiveSpiral->segmentColor[segment];
      GdkColor *new = old;

      if(color == Closure->redSector && old != Closure->redSector)
	new = color;

      if(   color == Closure->yellowSector
	 && old != Closure->redSector
	 && old != Closure->yellowSector)
	new = color;

      if(color == Closure->greenSector)
      {  rc->segmentState[segment]++;

	 if(rc->segmentState[segment] >= rc->sectorsPerSegment)
	   new = color;

	 /* Last segment represents less sectors */

	 if(   segment == Closure->readAdaptiveSpiral->segmentClipping - 1
	    && rc->segmentState[segment] >= rc->sectors % rc->sectorsPerSegment)
	   new = color;
      }

      if(new != old)
      {  ChangeSegmentColor(color, segment);
	 changed = TRUE;
      }
   }
   else changed = TRUE;

   if(changed)
     UpdateAdaptiveResults(rc->readable, rc->correctable, 
			   rc->sectors-rc->readable-rc->correctable,
			   (int)((1000LL*(rc->readable+rc->correctable))/rc->sectors));
}

/***
 *** Basic device and image handling and sanity checks.
 ***/

/*
 * Open CD/DVD device and .ecc file.
 * Determine reading mode.
 */

static void open_and_determine_mode(read_closure *rc)
{  unsigned char fp[16];
 
   /* open the device */

   rc->dh = OpenAndQueryDevice(Closure->device);
   rc->readMode = IMAGE_ONLY;

   /* save some useful information for the missing sector marker */

   if(GetMediumFingerprint(rc->dh, fp, FINGERPRINT_SECTOR))
   {  rc->fingerprint = g_malloc(16);
      memcpy(rc->fingerprint, fp, 16);
   }

   if(rc->dh->isoInfo && rc->dh->isoInfo->volumeLabel[0])
      rc->volumeLabel = g_strdup(rc->dh->isoInfo->volumeLabel);

   /* See if we have ecc information available. 
      Prefer the error correction file over augmented images if both are available. */

   /* See if the medium contains RS02 type ecc information */

   rc->ei = OpenEccFile(READABLE_ECC | PRINT_MODE);
   if(rc->ei)   /* RS01 type ecc */
   {  rc->readMode = ECC_IN_FILE;
      rc->eh = rc->ei->eh;

      rc->rs01LayerSectors = (rc->ei->sectors+rc->eh->dataBytes-1)/rc->eh->dataBytes;

      SetAdaptiveReadMinimumPercentage((1000*(rc->eh->dataBytes-rc->eh->eccBytes))/rc->eh->dataBytes);
   }
   else if(rc->dh->rs02Header)  /* see if we have RS02 type ecc */
   {  rc->readMode = ECC_IN_IMAGE;
      rc->eh  = rc->dh->rs02Header;
      rc->lay = CalcRS02Layout(uchar_to_gint64(rc->eh->sectors), rc->eh->eccBytes);
 
      SetAdaptiveReadMinimumPercentage((1000*rc->lay->ndata)/255);

      if(Closure->verbose)  /* for testing purposes */
      {  gint64 s,sinv,slice,idx;

	 for(s=0; s<rc->dh->sectors-1; s++)
	 {  RS02SliceIndex(rc->lay, s, &slice, &idx);
	    sinv = RS02SectorIndex(rc->lay, slice, idx);

	    if(slice == -1)
	       Verbose("Header %lld found at sector %lld\n", idx, s);
	    else
	    if(s != sinv) Verbose("Failed for sector %lld / %lld:\n"
				  "slice %lld, idx %lld\n",
				  s, sinv, slice, idx);
	 }
	 Verbose("RS02SliceIndex() verification finished.\n");
      }
   }

   /* Pick suitable message */

   switch(rc->readMode)
   {  case IMAGE_ONLY:
        rc->subtitle = g_strdup_printf(_("Stopping when unreadable intervals < %d."), 
				       Closure->sectorSkip);
	PrintLog(_("Adaptive reading: %s\n"), rc->subtitle); 
	break;

      case ECC_IN_FILE:
      case ECC_IN_IMAGE:
	rc->subtitle = g_strdup(_("Trying to collect enough data for error correction."));
	PrintLog(_("Adaptive reading: %s\n"), rc->subtitle);  
	break;
   }
}

/*
 * Validate image size against length noted in the ecc header
 */

static void check_size(read_closure *rc)
{  
   /* Number of sectors depends on ecc data */
 
   switch(rc->readMode)
   {  case IMAGE_ONLY:
        rc->sectors = rc->dh->sectors;
	return;

      case ECC_IN_FILE:
	rc->sectors = rc->ei->sectors;
	break;

      case ECC_IN_IMAGE:
	rc->sectors = rc->lay->eccSectors + rc->lay->dataSectors;
	break;
   }

   /* Compare size with answer from drive */

   if(rc->sectors < rc->dh->sectors)
   {  int answer;

      answer = ModalWarning(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, NULL,
			    _("Medium contains %lld sectors more as recorded in the .ecc file\n"
			      "(Medium: %lld sectors; expected from .ecc file: %lld sectors).\n"
			      "Only the first %lld medium sectors will be processed.\n"),
			    rc->dh->sectors-rc->sectors, rc->dh->sectors, rc->sectors,
			    rc->sectors);

      if(!answer)
      {  SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);
	 rc->earlyTermination = FALSE;
	 cleanup((gpointer)rc);
      }
   }

   if(rc->sectors > rc->dh->sectors)
   {  int answer;

      answer =  ModalWarning(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, NULL,
			     _("Medium contains %lld sectors less as recorded in the .ecc file\n"
			       "(Medium: %lld sectors; expected from .ecc file: %lld sectors).\n"),
			     rc->sectors-rc->dh->sectors, rc->dh->sectors, rc->sectors,
			     rc->sectors);

      if(!answer)
      {  SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);
	 rc->earlyTermination = FALSE;
	 cleanup((gpointer)rc);
      }

      rc->sectors = rc->dh->sectors;
   }
}

/*
 * Limit reading to user selected range
 */

void GetReadingRange(gint64 sectors, gint64 *firstSector, gint64 *lastSector)
{  gint64 first, last;

   if(Closure->readStart || Closure->readEnd)
   {  if(!Closure->guiMode) /* more range checks are made below */ 
      {  first = Closure->readStart;
         last  = Closure->readEnd < 0 ? sectors-1 : Closure->readEnd;
      }
      else  /* be more permissive in GUI mode */
      {  first = 0;
 	 last  = sectors-1;

	 if(Closure->readStart <= Closure->readEnd)
	 {  first = Closure->readStart < sectors ? Closure->readStart : sectors-1;
	    last  = Closure->readEnd   < sectors ? Closure->readEnd   : sectors-1;
	 }
      }

      if(first > last || first < 0 || last >= sectors)
	Stop(_("Sectors must be in range [0..%lld].\n"), sectors-1);

      PrintLog(_("Limiting sector range to [%lld,%lld].\n"), first, last);
   }
   else 
   {  first = 0; 
      last  = sectors-1;
   }

   *firstSector = first;
   *lastSector = last;
}

/*
 * Compare medium fingerprint against fingerprint stored in error correction file 
 */

static void check_ecc_fingerprint(read_closure *rc)
{  guint8 digest[16];
   int fp_read;

   fp_read = GetMediumFingerprint(rc->dh, digest, rc->eh->fpSector);

   if(!fp_read) /* Not readable. Bad luck. */
   {  int answer;

      answer = ModalWarning(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, NULL,
			    _("Sector %d is missing. Can not compare medium and ecc fingerprints.\n"
			      "Double check that the medium and the ecc file belong together.\n"),
			    rc->eh->fpSector);

      if(!answer)
      {  SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);
	 rc->earlyTermination = FALSE;
	 cleanup((gpointer)rc);
      }
   }
   else 
   {  
      if(memcmp(digest, rc->eh->mediumFP, 16))
	Stop(_("Fingerprints of medium and ecc file do not match.\n"
	       "Medium and ecc file do not belong together.\n"));
   }
}

/*
 * Compare image fingerprint with medium.
 */

int check_image_fingerprint(read_closure *rc)
{  struct MD5Context md5ctxt;
   guint8 image_fp[16], medium_fp[16];
   gint32 fingerprint_sector;
   int fp_read,n;
  
   /* Determine fingerprint sector */

   if(rc->eh)  /* If ecc information is present get fp sector number from there */
        fingerprint_sector = rc->eh->fpSector;
   else fingerprint_sector = FINGERPRINT_SECTOR;

   /* Try to read fingerprint sectors from medium and image */

   if(!LargeSeek(rc->image, (gint64)(2048*fingerprint_sector)))
     return 0; /* can't tell, assume okay */

   n = LargeRead(rc->image, rc->buf, 2048);
   MD5Init(&md5ctxt);
   MD5Update(&md5ctxt, rc->buf, 2048);
   MD5Final(image_fp, &md5ctxt);

   fp_read = GetMediumFingerprint(rc->dh, medium_fp, fingerprint_sector);

   if(n != 2048 || !fp_read || (CheckForMissingSector(rc->buf, fingerprint_sector, NULL, 0) != SECTOR_PRESENT))
     return 0; /* can't tell, assume okay */

   /* If both could be read, compare them */

   if(memcmp(image_fp, medium_fp, 16))
   {  	  
     if(!Closure->guiMode)
       Stop(_("Image file does not match the CD/DVD."));
     else
     {  int answer = ModalDialog(GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, NULL,
				 _("Image file already exists and does not match the CD/DVD.\n"
				   "The existing image file will be deleted."));
	   
        if(!answer)
	{  rc->earlyTermination = FALSE;
	   SetAdaptiveReadFootline(_("Reading aborted. Please select a different image file."), 
				   Closure->redText);
	   cleanup((gpointer)rc);
	}
	else
	{  LargeClose(rc->image);
	   LargeUnlink(Closure->imageName);
	   return TRUE; /* causes reopen of image in caller */
	} 
     }
   }

   return 0;  /* okay */
}

/*
 * Compare image size with medium.
 * TODO: image with byte sizes being not a multiple of 2048.
 */

void check_image_size(read_closure *rc, gint64 image_file_sectors)
{  
   if(image_file_sectors > rc->sectors)
   {  int answer;
	 
      answer = ModalWarning(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, NULL,
			    _("Image file is %lld sectors longer than inserted medium\n"
			      "(Image file: %lld sectors; medium: %lld sectors).\n"),
			    image_file_sectors-rc->sectors, image_file_sectors, rc->sectors);

      if(!answer)
      {  SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);
	 rc->earlyTermination = FALSE;
	 cleanup((gpointer)rc);
      }

      rc->highestWrittenSector = rc->sectors-1;
   }
   else rc->highestWrittenSector = image_file_sectors-1;
}

/***
 *** Load the crc buf from RS01/RS02 error correction data.
 ***/

static void load_crc_buf(read_closure *rc)
{
   switch(rc->readMode)
   {  case ECC_IN_FILE:
	 SetAdaptiveReadSubtitle(_utf("Loading CRC data."));
	 rc->crcBuf = GetCRCFromRS01(rc->ei);
	 break;
      case ECC_IN_IMAGE:
	 SetAdaptiveReadSubtitle(_utf("Loading CRC data."));
	 rc->crcBuf = GetCRCFromRS02(rc->lay, rc->dh, rc->image);
	 break;
      default:
	 rc->crcBuf = NULL;
	 break;
   }
}

/***
 *** Examine existing image file.
 ***
 * Build an initial interval list from it.
 */

static void build_interval_from_image(read_closure *rc)
{  gint64 s;
   gint64 first_missing, last_missing, current_missing;
   int tail_included = FALSE;
   int last_percent = 0;
   int crc_result;

   /*** Rewind image file */

   LargeSeek(rc->image, 0);
   first_missing = last_missing = -1;

   /*** Go through all sectors in the image file.
	Check them for "dead sector markers" 
	and for checksum failures if ecc data is present. */
   
   if(Closure->guiMode)
     SetAdaptiveReadSubtitle(_("Analysing existing image file"));

   for(s=0; s<=rc->highestWrittenSector; s++)
   {  int n,percent;

      /* Check for user interruption. */

      if(Closure->stopActions)   
      {  SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);
	 rc->earlyTermination = FALSE;
	 cleanup((gpointer)rc);
      }

      /* Read the next sector */

      n = LargeRead(rc->image, rc->buf, 2048);
      if(n != 2048) /* && (s != rc->sectors - 1 || n != ii->inLast)) */
	Stop(_("premature end in image (only %d bytes): %s\n"),n,strerror(errno));

      /* Look for the dead sector marker */

      current_missing = CheckForMissingSector(rc->buf, s, NULL, 0);

      if(current_missing)
      {  mark_sector(rc, s, Closure->redSector);
	 ExplainMissingSector(rc->buf, s, current_missing, TRUE);
      }

      /* Compare checksums if available */

      if(rc->crcBuf)
	   crc_result = CheckAgainstCrcBuffer(rc->crcBuf, s, rc->buf);
      else crc_result = CRC_UNKNOWN;

      switch(crc_result)
      {  case CRC_GOOD:
	    break;
	 case CRC_UNKNOWN:
	    break;
	 case CRC_BAD:
	    /* If its not already missing because of a read error,
	       make it missing due to the CRC failure. */
	    if(!current_missing)
	    {  current_missing = 1;
	       mark_sector(rc, s, Closure->yellowSector);
	    }
      }

      /* Remember sector state */

      if(current_missing)  /* Remember defect sector in current interval */
      {  if(first_missing < 0) first_missing = s;
	    last_missing = s;
      }
      else                 /* Remember good sector in eccStripe bitmap */
      {  rc->readable++;
	 if(rc->map)
	   SetBit(rc->map, s);

	 mark_sector(rc, s, Closure->greenSector);

#ifdef CHECK_VISITED
	 rc->count[s]++;
#endif
      }

      /* Determine end of current interval and write it out */

      if((!current_missing || s>=rc->highestWrittenSector) && first_missing>=0)
      {  if(s>=rc->highestWrittenSector)   /* special case: interval end = image end */
	 {  last_missing = rc->lastSector; /* may happen when image is truncated */
	    tail_included = TRUE;
	 }

	 /* Clip interval by user selected read range */

	 if(first_missing < rc->firstSector)  
	   first_missing = rc->firstSector;
	 if(last_missing > rc->lastSector)
	   last_missing = rc->lastSector;

	 /* add interval to list */

	 if(first_missing <= last_missing)
	   add_interval(rc, first_missing, last_missing-first_missing+1);

	 first_missing = -1;
      }

      /* Visualize the progress */

      percent = (100*s)/(rc->highestWrittenSector+1);
      if(last_percent != percent) 
      {  if(!Closure->guiMode)
	    PrintProgress(_("Analysing existing image file: %2d%%"),percent);

	 last_percent = percent;
      }
   }

   /*** If the image is shorter than the medium and the missing part
	was not already included in the last interval,
	insert another interval for the missing portion. */

   if(s<rc->lastSector && !tail_included)  /* truncated image? */
     add_interval(rc, s, rc->lastSector-s+1);

   /*** Now that all readable sectors are known,
	determine those which can already be corrected. */

   if(Closure->guiMode)
     SetAdaptiveReadSubtitle(_("Determining correctable sectors"));

   /* RS01 type error correction. */

   if(rc->readMode == ECC_IN_FILE)
   {  for(s=0; s<rc->rs01LayerSectors; s++)
      {  gint64 layer_idx;
	 int j,present=0;

	 /* Count available sectors in each layer */
	 
	 layer_idx = s;
	 for(j=0; j<rc->eh->dataBytes; j++)
	 {  if(   layer_idx >= rc->ei->sectors  /* padding sector */
	       || GetBit(rc->map, layer_idx))
	       present++;

	    layer_idx += rc->rs01LayerSectors;
	 }

	 /* See if remaining sectors are correctable */

	 if(rc->eh->dataBytes-present <= rc->eh->eccBytes)
	 {  layer_idx = s;
	    for(j=0; j<rc->eh->dataBytes; j++)   /* mark them as visited */
	    {  if(   layer_idx < rc->ei->sectors  /* skip padding sectors */
	          && !GetBit(rc->map, layer_idx))
	       {  SetBit(rc->map, layer_idx);
		  rc->correctable++;
#ifdef CHECK_VISITED
		  rc->count[layer_idx]++;
#endif
		  mark_sector(rc, layer_idx, Closure->greenSector);
	       }

	       layer_idx += rc->rs01LayerSectors;
	    }
	 }
      }
   }

   /* RS02 type error correction. */

   if(rc->readMode == ECC_IN_IMAGE)
   {  for(s=0; s<rc->lay->sectorsPerLayer; s++)
      {  int j,sector,present=0;

	 /* Count available sectors in each slice */
	 
	 for(j=0; j<255; j++)
	 {  sector = RS02SectorIndex(rc->lay, j, s);
	    if(   sector < 0  /* padding sector */ 
	       || GetBit(rc->map, sector))
	      present++;
	 }

	 /* See if remaining sectors are correctable */

	 if(255-present <= rc->eh->eccBytes)
	 {  for(j=0; j<255; j++)   /* mark them as visited */
	    {  sector = RS02SectorIndex(rc->lay, j, s);
	        if(   sector >= 0 /* don't mark the padding sector */
		   && !GetBit(rc->map, sector))
	       {  SetBit(rc->map, sector);
		  rc->correctable++;
		  mark_sector(rc, sector, Closure->greenSector);
	       }
	    }
	 }
      }
   }

   /*** Tell user results of image file analysis */

   if(rc->readMode == ECC_IN_FILE || rc->readMode == ECC_IN_IMAGE)
        PrintLog(_("Analysing existing image file: %lld readable, %lld correctable, %lld still missing.\n"),
		 rc->readable, rc->correctable, rc->sectors-rc->readable-rc->correctable);
   else PrintLog(_("Analysing existing image file: %lld readable, %lld still missing.\n"),
		 rc->readable, rc->sectors-rc->readable-rc->correctable);

   if(Closure->guiMode)
     UpdateAdaptiveResults(rc->readable, rc->correctable, 
			   rc->sectors-rc->readable-rc->correctable,
			   (int)((1000LL*(rc->readable+rc->correctable))/rc->sectors));

//   print_intervals(rc);
}

   /*** Mark RS02 header sectors as correctable.
        These are not part of any ecc block and have no influence on
	the decision when enough data has been gathered for error correction.
	Since they are needed for recognizing the image we will rewrite all
	them from the copy we got in rc->eh, but this can only be done when
	the image file has been fully created. */

static void mark_rs02_headers(read_closure *rc)
{  gint64 hpos, end;

   if(rc->readMode != ECC_IN_IMAGE) return;

   hpos = (rc->lay->protectedSectors + rc->lay->headerModulo - 1) / rc->lay->headerModulo;
   hpos *= rc->lay->headerModulo;
   end  = rc->lay->eccSectors + rc->lay->dataSectors - 2;

   while(hpos < end)
   {  if(!GetBit(rc->map, hpos))
      {  SetBit(rc->map, hpos);
	 mark_sector(rc, hpos, Closure->greenSector);
	 rc->correctable++;
      }
      if(!GetBit(rc->map, hpos+1))
      {  SetBit(rc->map, hpos+1);
         mark_sector(rc, hpos+1, Closure->greenSector);
	 rc->correctable++;
      }

      hpos += rc->lay->headerModulo;
   }
}

/***
 *** Main routine for adaptive reading
 ***/

static void insert_buttons(GtkDialog *dialog)
{  
  gtk_dialog_add_buttons(dialog, 
			 _utf("Ignore once"), 1,
			 _utf("Ignore always"), 2,
			 _utf("Abort"), 0, NULL);
} 

/*
 * Fill the gap between rc->intervalStart and rc->highestWrittenSector
 * with dead sector markers. These are needed in case the user aborts the operation; 
 * otherwise the gap will just be zero-filled and we don't know its contents
 * are unprocessed if we try to re-read the image later.
 * Also, this prevents fragmentation under most filesystems.
 */

void fill_gap(read_closure *rc)
{  char *anim[] = { ": |*.........|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |.*........|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |..*.......|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |...*......|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |....*.....|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |.....*....|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |......*...|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |.......*..|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |........*.|\b\b\b\b\b\b\b\b\b\b\b\b\b\b",
		    ": |.........*|\b\b\b\b\b\b\b\b\b\b\b\b\b\b"};
  char *t;
  gint64 i,j;
  gint64 firstUnwritten;

  /*** Start filling after rc->highestWrittenSector unless we are
       skipping from Sector 0 to the user selected start area. */

  if(rc->firstSector > 0 && rc->highestWrittenSector == 0)
       firstUnwritten = 0;
  else firstUnwritten = rc->highestWrittenSector + 1;

  /*** Tell user what's going on */

  t = g_strdup_printf(_("Filling image area [%lld..%lld]"), 
		      firstUnwritten, rc->intervalStart-1);
  clear_progress(rc);
  if(Closure->guiMode)
  {  SetAdaptiveReadSubtitle(t);
     ChangeSpiralCursor(Closure->readAdaptiveSpiral, -1); 
  }
  PrintCLI(t);
  g_free(t);

  /*** Seek to end of image */

  if(!LargeSeek(rc->image, (gint64)(2048*firstUnwritten)))
    Stop(_("Failed seeking to sector %lld in image [%s]: %s"),
	 firstUnwritten, "fill", strerror(errno));

  /*** Fill image with dead sector markers until rc->intervalStart */

  for(i=firstUnwritten, j=0; i<rc->intervalStart; i++)
  {  unsigned char buf[2048];
     int n;

     /* Write next sector */ 
    
     CreateMissingSector(buf, i, rc->fingerprint, FINGERPRINT_SECTOR, rc->volumeLabel);
     n = LargeWrite(rc->image, buf, 2048);
     if(n != 2048)
       Stop(_("Failed writing to sector %lld in image [%s]: %s"),
	    i, "fill", strerror(errno));

     /* Check whether user hit the Stop button */
	     
     if(Closure->stopActions)
     {  if(Closure->guiMode)
	 SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);

        rc->earlyTermination = FALSE;  /* suppress respective error message */
	cleanup((gpointer)rc);
     }

     /* Cycle the progress animation */

     if(j++ % 2000)
     {  int seq = (j/2000)%10;

	if(!Closure->guiMode)
	{  g_printf("%s", anim[seq]);
	   fflush(stdout);   /* at least needed for Windows */
	}
     }
	
     /* Show progress in the spiral */
    
     if(Closure->guiMode)
     {  int segment = i / rc->sectorsPerSegment;
       
        if(Closure->readAdaptiveSpiral->segmentColor[segment] == Closure->background)
	  ChangeSegmentColor(Closure->whiteSector, segment);
     }
  }

  PrintCLI("               \n");
  rc->highestWrittenSector = rc->intervalStart-1;

  if(Closure->guiMode)  /* remove temporary fill markers */
  {  RemoveFillMarkers();
     SetAdaptiveReadSubtitle(rc->subtitle);
  }
}


/*
 * If a correctable sector <correctable> lies beyond rc->highestWrittenSector,
 * fill the gap with dead sector markers.
 * So when reading resumes there will be no holes in the image.
 */

void fill_correctable_gap(read_closure *rc, gint64 correctable)
{  
   if(correctable > rc->highestWrittenSector)
   {  gint64 ds = rc->highestWrittenSector+1;
      unsigned char buf[2048];

      if(!LargeSeek(rc->image, (gint64)(2048*ds)))
	Stop(_("Failed seeking to sector %lld in image [%s]: %s"),
	     ds, "skip-corr", strerror(errno));

      for(ds=rc->highestWrittenSector+1; ds<=correctable; ds++)
      {  CreateMissingSector(buf, ds, rc->fingerprint, FINGERPRINT_SECTOR, rc->volumeLabel);
	 if(LargeWrite(rc->image, buf, 2048) != 2048)
	  Stop(_("Failed writing to sector %lld in image [%s]: %s"),
	       ds, "skip-corr", strerror(errno));
      }
      rc->highestWrittenSector = correctable;
   }
}

/*
 * The adaptive read strategy 
 */

void ReadMediumAdaptive(gpointer data)
{  read_closure *rc;
   gint64 s;
   gint64 image_file_size;
   int status,i,n;

   /*** Initialize the read closure. */

   rc = g_malloc0(sizeof(read_closure));

   rc->ab = CreateAlignedBuffer(MAX_CLUSTER_SIZE);
   rc->buf = rc->ab->buf;

   memset(rc->progressBs, '\b', 256);
   memset(rc->progressSp, ' ', 256);

   /*** Register the cleanup procedure so that Stop() can abort us properly. */

   rc->earlyTermination = TRUE;

   RegisterCleanup(_("Reading aborted"), cleanup, rc);
   if(Closure->guiMode)
     SetLabelText(GTK_LABEL(Closure->readAdaptiveHeadline), "<big>%s</big>\n<i>%s</i>",
		  _("Preparing for reading the medium image."),
		  _("Medium: not yet determined"));

   /*** Open Device and .ecc file. Determine read mode. */

   open_and_determine_mode(rc);

   /*** Compare image and ecc fingerprints (only if RS01 type .ecc is available) */

   if(rc->readMode == ECC_IN_FILE)
      check_ecc_fingerprint(rc);

   /*** Validate image size against ecc data */
   
   check_size(rc);

   /*** Limit the read range from users choice */

   GetReadingRange(rc->sectors, &rc->firstSector, &rc->lastSector);
   rc->intervalStart = rc->firstSector;
   rc->intervalEnd   = rc->lastSector;
   rc->intervalSize  = rc->intervalEnd - rc->intervalStart + 1;

   /*** Initialize the sector bitmap if ecc information is present.
	This is used to stop when sufficient data for error correction
	becomes available. */

   if(   rc->readMode == ECC_IN_FILE
      || rc->readMode == ECC_IN_IMAGE)
      rc->map = CreateBitmap0(rc->sectors);

#ifdef CHECK_VISITED
   rc->count = g_malloc0((int)rc->sectors+160);
#endif

   /*** Initialize segment state counters (only in GUI mode) */

   if(Closure->guiMode)
   {  //rc->sectorsPerSegment = 1 + (rc->sectors / ADAPTIVE_READ_SPIRAL_SIZE);
      rc->sectorsPerSegment = ((rc->sectors+ADAPTIVE_READ_SPIRAL_SIZE-1) / ADAPTIVE_READ_SPIRAL_SIZE);
      rc->segmentState = g_malloc0(ADAPTIVE_READ_SPIRAL_SIZE * sizeof(int));
      //      ClipReadAdaptiveSpiral(rc->sectors/rc->sectorsPerSegment);
      ClipReadAdaptiveSpiral((rc->sectors+rc->sectorsPerSegment-1)/rc->sectorsPerSegment);
   }

   /*** Initialize the interval list */

   rc->intervals = g_malloc(8*sizeof(gint64));
   rc->maxIntervals = 4; 
   rc->nIntervals = 0; 

   /*** Start with a fresh image file if none is already present. */

reopen_image:
   if(!LargeStat(Closure->imageName, &image_file_size))
   {  if(!(rc->image = LargeOpen(Closure->imageName, O_RDWR | O_CREAT, IMG_PERMS)))
	Stop(_("Can't open %s:\n%s"),Closure->imageName,strerror(errno));

      PrintLog(_("Creating new %s image.\n"),Closure->imageName);
      if(Closure->guiMode)
	SetLabelText(GTK_LABEL(Closure->readAdaptiveHeadline),
		     "<big>%s</big>\n<i>%s</i>",
		     _("Reading new medium image."),
		     rc->dh->mediumDescr);

      /* Mark RS02 header sectors as correctable. */

      mark_rs02_headers(rc);

      /* Preload the CRC buffer */

      load_crc_buf(rc);
   }

   /*** else examine the existing image file ***/

   else 
   {  int reopen;

      if(Closure->guiMode)
	SetLabelText(GTK_LABEL(Closure->readAdaptiveHeadline),
		     "<big>%s</big>\n<i>%s</i>",
		     _("Completing existing medium image."),
		     rc->dh->mediumDescr);

      /* Open the existing image file. */

      if(!(rc->image = LargeOpen(Closure->imageName, O_RDWR, IMG_PERMS)))
	Stop(_("Can't open %s:\n%s"),Closure->imageName,strerror(errno));

      /* See if the image fingerprint matches the medium */

      reopen = check_image_fingerprint(rc);
      if(reopen) 
	goto reopen_image;  /* no match, user wants to erase old image */

      /* Compare length of image and medium. */

      check_image_size(rc, image_file_size / 2048);

      /* Preload the CRC buffer */

      load_crc_buf(rc);

      /* Build the interval list */

      build_interval_from_image(rc);

      /* Mark still missing RS02 header sectors as correctable. */

      mark_rs02_headers(rc);

      /* Already enough information available? */
	 
      if(rc->readable + rc->correctable >= rc->sectors)
      {  char *t = _("\nSufficient data for reconstructing the image is available.\n");
	 PrintLog(t);
	 if(Closure->guiMode)
	   SetAdaptiveReadFootline(t, Closure->greenText);
	 goto finished;
      }

      /* Nope, begin with first interval */

      if(!rc->nIntervals)  /* may happen when reading range is restricted too much */
	goto finished;

      rc->intervalStart = rc->intervals[0];
      rc->intervalSize  = rc->intervals[1];
      rc->intervalEnd   = rc->intervalStart + rc->intervalSize - 1;
      pop_interval(rc);
   }

   /*** Read the medium image. */

   if(Closure->guiMode)
     SetAdaptiveReadSubtitle(rc->subtitle);

   for(;;)
   {  int cluster_mask = rc->dh->clusterSize-1;

      /* If we jumped beyond the highest writtensector, 
	 fill the gap with dead sector markers. */

      if(rc->intervalStart > rc->highestWrittenSector)
	fill_gap(rc);

      /*** Try reading the next interval */

      print_progress(rc, TRUE);

      for(s=rc->intervalStart; s<=rc->intervalEnd; ) /* s is incremented elsewhere */
      {  int nsectors,cnt;
 
	 if(Closure->stopActions)          /* somebody hit the Stop button */
	 {  if(Closure->guiMode)
	       SetAdaptiveReadFootline(_("Aborted by user request!"), Closure->redText);

	    rc->earlyTermination = FALSE;  /* suppress respective error message */
	    goto terminate;
	 }

	 if(Closure->guiMode)
	    ChangeSpiralCursor(Closure->readAdaptiveSpiral, s / rc->sectorsPerSegment);
	    
	 /* Determine number of sectors to read. Read the next dh->clusterSize sectors
	    unless we're at the end of the interval or at a position which is
	    not divideable by the cluster size. */

	 if(s & cluster_mask)
               nsectors = 1;
	 else  nsectors = rc->dh->clusterSize;

	 if(s+nsectors > rc->intervalEnd) nsectors = rc->intervalEnd-s+1;

	 /* Skip sectors which have been marked as correctable by
	    ecc information. */

	 if(rc->map)
	 {  for(i=cnt=0; i<nsectors; i++)  /* sectors already present? */
	    {  int idx = s+i;

	       if(GetBit(rc->map, idx))
		 cnt++;
	    }

	    /* Shift the outer loop down to 1 sector per read.
	       Short circuit the outer loop if the sector is already present. */

	    if(cnt) 
	    {  nsectors = 1;

	       if(GetBit(rc->map, s))
	       {  s++;
		  continue;  /* restart reading loop with next sector */
	       }
	    }
	 }

	 /* Try to actually read the next sector(s) */
reread:
	 status = ReadSectors(rc->dh, rc->buf, s, nsectors);

	 /* Medium Error (3) and Illegal Request (5) may result from 
	    a medium read problem, but other errors are regarded as fatal. */

	 if(status && !Closure->ignoreFatalSense
	    && rc->dh->sense.sense_key 
	    && rc->dh->sense.sense_key != 3 && rc->dh->sense.sense_key != 5)
	 {  int answer;

	    if(!Closure->guiMode)
	      Stop(_("Sector %lld: %s\nCan not recover from above error.\n"
		     "Use the --ignore-fatal-sense option to override."),
		   s, GetLastSenseString(FALSE));

	    answer = ModalDialog(GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, insert_buttons,
				 _("Sector %lld: %s\n\n"
				   "It may not be possible to recover from this error.\n"
				   "Should the reading continue and ignore this error?"),
				 s, GetLastSenseString(FALSE));

	    if(answer == 2)
	      Closure->ignoreFatalSense = 2;

	    if(!answer)
	    {  SetAdaptiveReadFootline(_("Aborted by unrecoverable error."), Closure->redText);

	       rc->earlyTermination = FALSE;  /* suppress respective error message */
	       goto terminate;
	    }
	 }

	 /* When encountering an error during cluster size reads,
	    try again reading each sector one by one.
	    Otherwise we skip cluster size chunks until the unreadable
	    intervals become smaller than the cluster size. */

	 if(status && nsectors > 1)
	 {  nsectors = 1;
	    goto reread;
	 }

	 /* Reading was successful. */

	 if(!status)   
	 {  gint64 b;

	    if(!LargeSeek(rc->image, (gint64)(2048*s)))
	      Stop(_("Failed seeking to sector %lld in image [%s]: %s"),
		   s,"store",strerror(errno));

	    /* Store sector(s) in the image file if they pass the CRC test,
	       otherwise treat them as unprocessed. */

	    for(i=0, b=s; i<nsectors; i++,b++)
	    {  int result;
	       int err;

	       /* Calculate and compare CRC sums.
		  Sectors with bad CRC sums are marked unvisited,
		  but do not terminate the current interval. */

	       if(rc->crcBuf) /* we have crc information */
		    result = CheckAgainstCrcBuffer(rc->crcBuf, b, rc->buf+i*2048);
	       else result = CRC_UNKNOWN;

	       switch(result)
	       {  case CRC_BAD:
		  {  //unsigned char buf[2048];

		     PrintCLI("\n");
		     PrintCLI(_("CRC error in sector %lld\n"),b);
		     print_progress(rc, TRUE);

#if 0 // remark: Do we still need to mark CRC defects as completely missing?
		     CreateMissingSector(buf, b, rc->fingerprint, FINGERPRINT_SECTOR, rc->volumeLabel);
		     n = LargeWrite(rc->image, buf, 2048);
#endif
		     n = LargeWrite(rc->image, rc->buf+i*2048, 2048);
		     if(n != 2048)
			Stop(_("Failed writing to sector %lld in image [%s]: %s"),
			     b, "unv", strerror(errno));

		     mark_sector(rc, b, Closure->yellowSector);
		     
		     if(rc->highestWrittenSector < b)
			rc->highestWrittenSector = b;
		     break;
		  }
		  case CRC_UNKNOWN:
		  case CRC_GOOD:
		     n = LargeWrite(rc->image, rc->buf+i*2048, 2048);
		     if(n != 2048)
			Stop(_("Failed writing to sector %lld in image [%s]: %s"),
			     b, "store", strerror(errno));

		     if(rc->map)
			SetBit(rc->map, b);
		     rc->readable++;

		     mark_sector(rc, b, Closure->greenSector);
		    
		     if(rc->highestWrittenSector < b)
			rc->highestWrittenSector = b;
		     break;
	       }

	       /*** Warn the user if we see dead sector markers on the image.
		    Note: providing the fingerprint is not necessary as any 
		    incoming missing sector marker indicates a huge problem. */

	       err = CheckForMissingSector(rc->buf+i*2048, b, NULL, 0);
	       if(err != SECTOR_PRESENT)
	       {  ExplainMissingSector(rc->buf+i*2048, b, err, FALSE);

		  if(rc->map)  /* Avoids confusion in the ecc stage */
		     ClearBit(rc->map, b);
		  rc->readable--;
	       }
	    }

	    /* See if additional sectors become correctable. */
	    
	    if(rc->readMode == ECC_IN_FILE)  /* RS01 type ecc data */
	    {  for(i=0, b=s; i<nsectors; i++,b++) 
	       {  int j,present=0;
		  gint64 layer_idx;

#ifdef CHECK_VISITED
		  rc->count[b]++;
#endif
		  /* Count available sectors. */

		  layer_idx = b % rc->rs01LayerSectors;
		  for(j=0; j<rc->eh->dataBytes; j++) 
		  {  if(   layer_idx >= rc->ei->sectors /* padding sector */
			|| GetBit(rc->map, layer_idx))
			present++;
		     layer_idx += rc->rs01LayerSectors;
		  }

		  /* If the remaining sectors are correctable,
		     mark them as visited. */

		  if(rc->eh->dataBytes-present <= rc->eh->eccBytes)
		  {  layer_idx = b % rc->rs01LayerSectors;

		     for(j=0; j<rc->eh->dataBytes; j++)
		     {  if(   layer_idx < rc->ei->sectors /* skip padding sector */
			   && !GetBit(rc->map, layer_idx))
			{  SetBit(rc->map, layer_idx);
			   rc->correctable++;
			   mark_sector(rc, layer_idx, Closure->greenSector);

#ifdef CHECK_VISITED
			   rc->count[layer_idx]++;
#endif

			   /* If the correctable sector lies beyond the highest written sector,
			      fill the gap with dead sector markers */

			   fill_correctable_gap(rc, layer_idx);

			}
		        layer_idx += rc->rs01LayerSectors;
		     }
		  }
	       }
	    }

	    if(rc->readMode == ECC_IN_IMAGE)  /* RS02 type ecc data */
	    {  for(i=0, b=s; i<nsectors; i++,b++) 
	       {  int j,present=0;
		  gint64 slice_idx, ignore, sector;

		  /* Count available sectors. */

		  RS02SliceIndex(rc->lay, b, &ignore, &slice_idx);
		  for(j=0; j<255; j++) 
		  {  sector = RS02SectorIndex(rc->lay, j, slice_idx);
		     if(   sector < 0  /* padding sector */ 
			|| GetBit(rc->map, sector))
			present++;
		  }

		  /* If the remaining sectors are correctable,
		     mark them as visited. */

		  if(255-present <= rc->eh->eccBytes)
		  {  for(j=0; j<255; j++)
		     {  sector = RS02SectorIndex(rc->lay, j, slice_idx);
		        if(   sector >= 0 /* don't mark the padding sector */
			   && !GetBit(rc->map, sector))
			{  SetBit(rc->map, sector);
			   rc->correctable++;
			   mark_sector(rc, sector, Closure->greenSector);
			   fill_correctable_gap(rc, sector);
			}
		     }
		  }
	       }
	    }

	    /* Increment sector counters. Adjust max image sector
	       if we added sectors beyond the image size. */

	    s+=nsectors;
#if 0 /* obsoleted since it is carried out right after the LargeWrite() above */
	    if(s>rc->highestWrittenSector) rc->highestWrittenSector=s;
#endif

	    /* Stop reading if enough data for error correction
	       has been gathered */

	    if(rc->readable + rc->correctable >= rc->sectors)
	    {  char *t = _("\nSufficient data for reconstructing the image is available.\n");

	       print_progress(rc, TRUE);
	       PrintLog(t);
	       if(Closure->guiMode && rc->ei)
		  SetAdaptiveReadFootline(t, Closure->foreground);
	       if(Closure->eject)
		  LoadMedium(rc->dh, FALSE);
	       goto finished;
	    }
	 }  /* end of if(!status) (successful reading of sector(s)) */

	 else  /* Process the read error. */
	 {  unsigned char buf[2048];

	    PrintCLI("\n");
	    if(nsectors>1) PrintCLIorLabel(Closure->status,
					   _("Sectors %lld-%lld: %s\n"),
					   s, s+nsectors-1, GetLastSenseString(FALSE));  
	    else	   PrintCLIorLabel(Closure->status,
					   _("Sector %lld: %s\n"),
					   s, GetLastSenseString(FALSE));  

	    rc->unreadable += nsectors;

	    /* Write nsectors of "dead sector" markers */

	    if(!LargeSeek(rc->image, (gint64)(2048*s)))
	      Stop(_("Failed seeking to sector %lld in image [%s]: %s"),
		   s, "nds", strerror(errno));

	    for(i=0; i<nsectors; i++)
	    {  CreateMissingSector(buf, s+i, rc->fingerprint, FINGERPRINT_SECTOR, rc->volumeLabel);

	       n = LargeWrite(rc->image, buf, 2048);
	       if(n != 2048)
		 Stop(_("Failed writing to sector %lld in image [%s]: %s"),
		      s, "nds", strerror(errno));

	       mark_sector(rc, s+i, Closure->redSector);
	    }

	    if(rc->highestWrittenSector < s+nsectors)
	      rc->highestWrittenSector = s+nsectors-1;

	    /* Reading of the interval ends at the first read error.
	       Store the remainder of the current interval in the queue. */

	    if(s+nsectors-1 >= rc->intervalEnd)  /* This was the last sector; interval used up */
	    {  Verbose("... Interval [%lld..%lld] used up\n", rc->intervalStart, rc->intervalEnd);
	    }
	    else  /* Insert remainder of interval into queue */
	    {  rc->intervalStart = s+nsectors;
	       rc->intervalSize  = rc->intervalEnd-rc->intervalStart+1;

	       Verbose("... Interval %lld [%lld..%lld] added\n", 
		       rc->intervalSize, rc->intervalStart, rc->intervalStart+rc->intervalSize-1);

	       add_interval(rc, rc->intervalStart, rc->intervalSize);
	       //print_intervals(rc);
	    }
	    break; /* fall out of reading loop */
	 }

	 print_progress(rc, FALSE);
      }

      /* If we reach this, the current interval has either been read completely
	 or the loop was terminated early by a read error. 
         In both cases, the current interval has already been remove from the queue
         and the queue contains only the still unprocessed intervals. */

      if(s>=rc->intervalEnd) /* we fell out of the reading loop with interval completed */
      {  print_progress(rc, TRUE);
	 PrintCLI("\n");
      }

      /* Pop the next interval from the queue,
         prepare one half from it for processing
         and push the other half back on the queue. */

      if(rc->nIntervals <= 0)
	goto finished;

      rc->intervalStart = rc->intervals[0];
      rc->intervalSize  = rc->intervals[1];
      pop_interval(rc);

      /* Split the new interval */

      if(rc->intervalSize>1)
      {  Verbose("*** Splitting [%lld..%lld]\n",
		 rc->intervalStart,rc->intervalStart+rc->intervalSize-1);

	 add_interval(rc, rc->intervalStart, rc->intervalSize/2);
	 rc->intervalEnd = rc->intervalStart+rc->intervalSize-1;
	 rc->intervalStart = rc->intervalStart+rc->intervalSize/2;
      }
      else /* 1 sector intervals can't be split further */
      {  
	 rc->intervalEnd = rc->intervalStart;
	 Verbose("*** Popped [%lld]\n",rc->intervalStart);
      }

      //print_intervals(rc);

      rc->intervalSize  = rc->intervalEnd-rc->intervalStart+1;

      /* Apply interval size termination criterion */

      if(rc->intervalSize < Closure->sectorSkip)
	 goto finished;
   }

finished:

#ifdef CHECK_VISITED
   {  int i,cnt=0;
      for(i=0; i<(int)rc->sectors; i++)
      {  cnt+=rc->count[i];
         if(rc->count[i] != 1)
           printf("Sector %d: %d\n",i,rc->count[i]);
      }

      printf("\nTotal visited %d (%d)\n",cnt,i);

      for(i=(int)rc->sectors; i<(int)rc->sectors+160; i++)
        if(rc->count[i] != 0)
          printf("SECTOR %d: %d\n",i,rc->count[i]);
   }
#endif

   /* Force output of final results */

   if(Closure->guiMode)
   {  ChangeSpiralCursor(Closure->readAdaptiveSpiral, -1);
      mark_sector(rc, 0, NULL);
   }

   /*** Summarize results. */

   /* We were in ECC_IN_FILE or ECC_IN_IMAGE mode,
      but did not recover sufficient data. */

   if(rc->map && (rc->readable + rc->correctable < rc->sectors))
   {  int total = rc->readable+rc->correctable;
      int percent = (int)((1000LL*(long long)total)/rc->sectors);
      char *t = g_strdup_printf(_("Only %2d.%1d%% of the image are readable or correctable"),
				  percent/10, percent%10); 

      PrintLog(_("\n%s\n"
		  "(%lld readable,  %lld correctable,  %lld still missing).\n"),
		t, rc->readable, rc->correctable, rc->sectors-total);
      if(Closure->guiMode)
	 SetAdaptiveReadFootline(t, Closure->foreground);

      g_free(t);
      exitCode = EXIT_FAILURE;
   }

   /* Results for reading in IMAGE_ONLY mode */

   if(rc->readMode == IMAGE_ONLY)
   {  if(rc->readable == rc->sectors)
      {  char *t = _("\nGood! All sectors have been read.\n"); 
	 PrintLog(t);
	 if(Closure->guiMode)
	   SetAdaptiveReadFootline(t, Closure->foreground);
	 if(Closure->eject)
	    LoadMedium(rc->dh, FALSE);
      }
      else
      {  int percent = (int)((1000LL*rc->readable)/rc->sectors);
	 char *t = g_strdup_printf(_("No unreadable intervals with >= %d sectors left."),
				   Closure->sectorSkip);

	 PrintLog(_("\n%s\n" 
		     "%2d.%1d%% of the image have been read (%lld sectors).\n"),
		   t, percent/10, percent%10, rc->readable);

	 if(Closure->guiMode)
	   SetAdaptiveReadFootline(t, Closure->foreground);
	 g_free(t);
	 exitCode = EXIT_FAILURE;
      }
   }

#if 0
   for(i=0; i<rc->sectors; i++)
     if(!GetBit(rc->map, i))
       printf("Missing: %d\n", i);
#endif

   /*** Close and clean up */

   rc->earlyTermination = FALSE;

terminate:
   cleanup((gpointer)rc);
}