/* Routines to read and write sectors
** Only one copy of a particular sector will be stored, to prevent
** inconsistency.
** Written by Peter Wu 7/11/86 @ Faculty Support Center @ Univ. of Wisconsin
** This is used by the mv (move files and directory) program.
** Link with absdr (source absdr.asm)
*/
#define LINT_ARGS

#define  MAX_SECTOR_SIZE  4200	/* is this safe enough? */
#define  MAX_COPIES  5		/* max # of sectors buffered */

#include <conio.h>

/* global stuff */

char secbufx[MAX_SECTOR_SIZE * MAX_COPIES], dirty[MAX_COPIES];
int secind[MAX_COPIES], drvind[MAX_COPIES];
int num_sec;  /* number of sectors currently buffered */

char *readsec(drv, sector)  /* read a sector; return pointer to buffer */
int drv, sector;
{
  int i, status;
  char *where;

#ifdef debug
  printf("reading sector# %d\n",sector);
#endif
  /* first see if the sector requested is already in buffer */
  for (i=0; i < num_sec; i++) {
    if ((secind[i] == sector) &&
	(drvind[i] == drv)	) {  /* aha - sector already read */
      return secbufx + i * MAX_SECTOR_SIZE;  /* return pointer to buffer */
    }
  }

  /* sector is not in buffer, so read it, but first allocate a buffer */
  secind[num_sec] = sector;  /* store sector number */
  drvind[num_sec] = drv;
  where = secbufx + num_sec * MAX_SECTOR_SIZE;
  status = absdr(drv, 1, sector, where);
  if (status) {
    cputs("Error in readsec calling absdr\n\015");
    return (char *) 0;
  }
  dirty[num_sec] = 0;  /* not dirty */
  num_sec++;

  /* successfully read a sector into buffer */
  return where;
}

writesec(drv,sector)
int drv, sector;
{
  int i, status;

#ifdef debug
  printf("writing sector# %d\n", sector);
#endif
  for (i=0; i < num_sec; i++) {
    if ((secind[i] == sector) && (drvind[i] == drv)) {
      if (dirty[i]) {  /* write the sector only if it's dirty */
	status = absdw(drvind[i], 1, secind[i], secbufx + i * MAX_SECTOR_SIZE);
	if (status) {
	  cputs("Error in flushsec calling absdw\n\015");
	  return -1;
	} else {
	  dirty[i] = 0;
	}
      }
      return 0;
    }
  }  /* for */
  cputs("writesec: sector is not in buffer\n\015");
  return -2;
}

flirt(drv,sector)  /* turn on dirty flag */
int drv,sector;
{
  int i;

#ifdef debug
  printf("flirting sector# %d; num_sec = %d\n",sector,num_sec);
#endif
  for (i=0; i < num_sec; i++) {
    if ((secind[i] == sector) && (drvind[i] == drv)) {
      dirty[i] = 1;
      return 0;
    }
  }
  cputs("flirt: can't find sector to flirt with\n\015");
  return -1;
}
