Logo Search packages:      
Sourcecode: cbmconvert version File versions  Download package

static int write_sector ( unsigned  sect  )  [static]

Encode a sector

Parameters:
sect the sector number
Returns:
0 on success; 1 on failure

Definition at line 141 of file disk2zip.c.

References outfile, track, and trackbuf.

Referenced by write_track().

{
  /* a histogram: number of occurrences of different bytes */
  static int histogram[256];
  int i;
  unsigned char* sectbuf = trackbuf[sect];

  memset (histogram, 0, sizeof histogram);

  /* see if the all bytes in the sector are identical */
  for (i = 0; i < 256; i++)
    if (256 == ++histogram[sectbuf[i]])
      return EOF == fputc (track | 0x40, outfile) ||
             EOF == fputc (sect, outfile) ||
             EOF == fputc (sectbuf[i], outfile);

  /* see whether there is a byte that does not occur in the sector */
  for (i = 0; i < 256 && histogram[i]; i++);

  /* if not, store the sector without compression */
  if (i > 255)
Uncompressed:
    return EOF == fputc (track, outfile) ||
           EOF == fputc (sect, outfile) ||
           1 != fwrite (sectbuf, 256, 1, outfile);
  /* otherwise, see if run-length encoding would bring savings */
  else {
    int rep = i, j, count;
    for (i = 1, j = count = 0; i < 256; i++) {
      if (sectbuf[i] == sectbuf[j])
      continue;
      count += (i < j + 3) ? i - j : 3;
      j = i;
    }
    count += (i < j + 3) ? i - j : 3;

    if (count > 253)
      goto Uncompressed;

    /* apply run-length encoding */
    if (EOF == fputc (track | 0x80, outfile) || EOF == fputc (sect, outfile) ||
      EOF == fputc (count, outfile) || EOF == fputc (rep, outfile))
      return 1;

    for (i = 1, j = 0;; i++) {
      if (i < 256 && sectbuf[i] == sectbuf[j])
      continue;
      if (i > j + 3) {
      if (EOF == fputc (rep, outfile) || EOF == fputc (i - j, outfile) ||
          EOF == fputc (sectbuf[j], outfile))
        return 1;
      }
      else if (1 != fwrite (&sectbuf[j], i - j, 1, outfile))
        return 1;

      if (i > 255)
      break;
      j = i;
    }

    return 0;
  }
}


Generated by  Doxygen 1.6.0   Back to index