/*
 * fileio.c  -  File I/O routines
 *
 * Copyright (C) 1998-2007 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  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
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: fileio.c,v 1.12 2007/01/06 18:31:38 gkminix Exp $
 */

#include <common.h>
#include <nblib.h>
#include "privlib.h"



/*
 * Global variables exported by this module
 */
unsigned long write_chksum = 0;	/* checksum for all bytes when writing */



/*
 * Read one block of data
 */
size_t nbread __F((buf, bufsize, infile),
				__u8 *buf AND
				size_t bufsize AND
				int infile)
{
  long ofs;

  if (bufsize == 0)
	return(0);

  /*
   * We assume here that read() really reads the input file byte by byte,
   * and also stores each byte into a packed array of bytes. There do exist
   * systems with a character size different that one byte. How should we
   * handle those?
   */
  if ((ofs = read(infile, (char *)buf, bufsize)) < 0) {
	if (!quiet) perror(progname);
	nbexit(EXIT_READ);
  }
  return(ofs);
}



/*
 * Write one block of data to the output file.
 */
size_t nbwrite __F((buf, bufsize, outfile),
				__u8 *buf AND
				size_t bufsize AND
				int outfile)
{
  long j, ofs;

  if (bufsize == 0)
	return(0);

  /*
   * Write buffer into output file. The same problem with read() above also
   * applies to write(). Can we assume, that it will write a packed array of
   * bytes correctly?
   */
  if ((ofs = write(outfile, (char *)buf, bufsize)) < 0) {
	if (!quiet) perror(progname);
	nbexit(EXIT_WRITE);
  }
  if ((size_t)ofs != bufsize) {
	prnerr("incorrect number of bytes written");
	nbexit(EXIT_WRITE);
  }

  /* Compute the checksum */
  for (j = 0; j < ofs; j++) {
	write_chksum += buf[j];
	write_chksum &= 0xffff;
  }
  return((size_t)ofs);
}

