/*
 * RCS_ID_C="$Id: _write.c,v 4.1 1994/09/29 23:09:02 jraja Exp $";
 *	_write.c - write() for both files and sockets (SAS/C)
 *
 *	Copyright © 1994 AmiTCP/IP Group,
 *			 Network Solutions Development Inc.
 *			 All rights reserved.
 */
#define KERNEL
#define _INTERNAL_FILE
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <dos/dos.h>
#include <proto/dos.h>
#include <sys/file.h>
#include <fcntl.h>
#include <bsdsocket.h>
#include <sys/syslog.h>

extern int __ioerr_to_errno(long);
extern int errno;

int
__tcpwrite(struct file *ufb, char *buffer, unsigned int length)
{
  int	      count, totcount;
  char	     *ptr;

  if (ufb->f_type != DTYPE_SOCKET) syslog(LOG_ERR,"__tcpwrite found a nonsocket.");

  /*
   * Check if write is allowed
   */
  if (!(ufb->f_flags & FWRITE)) {
    errno = EIO;
    return -1;
  }

  /*
   * Check if translation is not needed
   */
  if (!(ufb->f_flags & O_XLATE) ||
      (ptr = memchr(buffer, 0x0A, length)) == NULL) {
    if ((count = send((LONG)ufb->f_fh, (char *)buffer, length, 0)) < 0)
      return -1;
    return count;
  }

  totcount = length;

  /*
   * Translate, ie., append CR before each LF
   */
  do {
    count = ptr - (char *)buffer;
    if (send((LONG)ufb->f_fh, (char *)buffer, count, 0) < 0)
      return -1;
    if (send((LONG)ufb->f_fh, "\015"/* CR */, 1, 0) < 0)
      return -1;
    length -= count;

    buffer = ptr;
  } while ((ptr = memchr((char *)buffer + 1, 0x0A, length)) != NULL);

  if ((count = send((LONG)ufb->f_fh, (char *)buffer, length, 0)) < 0)
    return -1;

  return totcount;

osfail:
  errno = __ioerr_to_errno(IoErr());
  return -1;
}
