/*
 *		Cross Development System for Atari ST 
 *     Copyright (c) 1988, Memorial University of Newfoundland
 *
 * See Changelog for further history	++jrb
 *
 * 1.5  ERS -- modified for 16 bit compilers
 * 1.4  ERS -- added errno handling, fixed up calls to console_write_byte
 *
 * 1.3	jrd
 *
 * Revision 1.2  88/02/03  22:56:45  m68k
 * Added unix like tty driver stuff
 * 
 * Revision 1.1  88/01/29  17:32:06  m68k
 * Initial revision
 * 
 */
#include	<stddef.h>
#include	<errno.h>
#include	<osbind.h>
#include	<ioctl.h>
#include	<tchars.h>
#include	<unistd.h>
#include	<string.h>
#include	<device.h>
#include	<limits.h>
#include 	<fcntl.h>
#include	"lib.h"

int	__col_pos = 0;

#ifdef __MSHORT__
int
write(fd, buf, nbytes)
	int		fd;
	const void	*buf;
	unsigned int	nbytes;
{
       return _write(fd, buf, (unsigned long)nbytes);
}
#else

asm(".stabs \"_write\",5,0,0,__write"); /* dept of clean tricks */

#endif
long
_write(fd, buf, n)
      int     fd;
      const void *buf;
      unsigned long  n;
{
  long nbytes;
  const char	*s;
  long i;
  long result;
  struct _device *dev;

  if(n > ((unsigned long)LONG_MAX))
  {
    errno = EBADARG;
    return -1L;
  }
  nbytes = (long)n;
  if ((dev = _dev_fd(fd)) && dev->write)
	return (*dev->write)(fd, buf, nbytes);

  if (!isatty(fd)) {
	int f = __OPEN_INDEX(fd);
	
	if( (f >= __NHANDLES) || (f < 0) )
	{
	    errno = EBADF;
	    return -1;
	}

	if (__open_stat[f].append) { /* if O_APPEND */
	    result = Fseek(0L, fd, SEEK_END);
            if (result < 0) {
                errno = -result;
                return(-1L);
            }
	}

        result = Fwrite(fd, nbytes, buf);
	if (result < 0) {
		errno = -result;
		return -1L;
	}
	else return result;
  }

  i = nbytes;
  for (s = buf; i > 0 ; s++, i-- ) {
	if (*s == '\n' && (__ttymode & CRMOD) && !(__ttymode & RAW)) 
		{
		console_write_byte(fd, '\r');
		console_write_byte(fd, '\n');
		__col_pos = 0;
		} 
	    else
		{
		if (*s == '\r')
			__col_pos = 0;
		    else
		if (*(unsigned char *)s >= ' ')
			__col_pos++;
		    else
		if (*s == '\t')
			__col_pos = (__col_pos | 7) + 1;
		console_write_byte(fd, *s);
		}
  }
  return nbytes;
}
