/*
 *	read() - a quick stand alone version for lev1boot.c
 *		to use for loading programs
 *
 *	NOTE IMPORTANT LIMITATIONS:
 *		only one "file" active at a time
 *		you must call resetread() when you change files
 *		(YES THIS IS A HACK! - If you don't like it, fix it)
 */

#include "ktypes.h"
#include "filesys.h"

static char frob[]="$Header: read.c,v 1.3 87/02/25 11:04:18 tom Exp $";


static char IOBUFF[BLKSZ];		/* a local buffer for I/O */
static int mybno;
static int bytesleft;

static char *myptr = &IOBUFF[0];	/* need to remember where we were in the buffer */


/* we are through with whatever file we were reading from, get ready
   to read from some other...
*/
resetread()
{
  register int i;
  
  mybno = 0;
  bytesleft = 0;
  myptr = &IOBUFF[0];
  for (i=0;i<BLKSZ;i++)
    IOBUFF[i]= 0;
}



read(fp,bptr,bsize)
     struct filep *fp;		/* a filep to the file */
     char *bptr;		/* ptr to buffer (physical memory, usually) */
     int bsize;			/* number of bytes to get */
{
  register char *mybptr= bptr;
  register int mybsize = bsize;

  if (mybsize == 0)
    return (0);
  
#ifdef DEBUG
printf("read: mybptr 0x%X, bsize %d, current file block %d, bytesleft %d, buff offset %d\n",
       mybptr,mybsize, mybno, bytesleft, (myptr- &IOBUFF[0]));
#endif

  while (mybsize)
    {
      if (bytesleft == 0)
	{
	  if (get_file_block(fp,mybno,&IOBUFF[0]) < 0) 
	    {
	      printf("Trouble reading file: block # %d\n",mybno);
	      return(-1);
	    }
	  bytesleft = 512;
	  myptr = &IOBUFF[0];
	  mybno++;
	}

      *mybptr++ = *myptr++;
      bytesleft--;
      mybsize--;
    }
  return(bsize);
}

