ExternalStream.st
author Claus Gittinger <cg@exept.de>
Sun, 07 Apr 1996 04:12:19 +0200
changeset 1141 8ea1b43f7034
parent 1138 993e6ffdbf51
child 1281 b4b3abffdf32
permissions -rw-r--r--
*** empty log message ***

"
 COPYRIGHT (c) 1988 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"

'From Smalltalk/X, Version:2.10.9 on 7-mar-1996 at 11:06:07'                    !

ReadWriteStream subclass:#ExternalStream
	instanceVariableNames:'filePointer mode buffered binary useCRLF hitEOF didWrite
		lastErrorNumber'
	classVariableNames:'Lobby LastErrorNumber InvalidReadSignal InvalidWriteSignal
		InvalidModeSignal OpenErrorSignal StreamNotOpenSignal
		InvalidOperationSignal'
	poolDictionaries:''
	category:'Streams-External'
!

!ExternalStream primitiveDefinitions!
%{
#include <stdio.h>
#define _STDIO_H_INCLUDED_

#include <fcntl.h>
#define _FCNTL_H_INCLUDED_

#include <errno.h>
#define _ERRNO_H_INCLUDED_

#ifdef LINUX
  /* use inline string macros */
# define __STRINGDEFS__
# include <linuxIntern.h>
#endif

#ifdef hpux
# define fileno(f)      ((f->__fileH << 8) | (f->__fileL))
#endif

#ifndef SEEK_SET
# define SEEK_SET 0
#endif
#ifndef SEEK_CUR
# define SEEK_CUR 1
#endif
#ifndef SEEK_END
# define SEEK_END 2
#endif

/*
 * stdio library requires an fseek before reading whenever a file
 * is open for read/write and the last operation was a write.
 * (also vice-versa).
 * All code should use the following macro before doing reads:
 */
#define __READING__(f)                          \
    if ((__INST(didWrite) != false)              \
     && (__INST(mode) == @symbol(readwrite))) {  \
	__INST(didWrite) = false;                \
	fseek(f, 0L, SEEK_CUR); /* needed in stdio */  \
    }

#define __WRITING__(f)                          \
    if ((__INST(didWrite) != true)               \
     && (__INST(mode) == @symbol(readwrite))) {  \
	__INST(didWrite) = true;                 \
	fseek(f, 0L, SEEK_CUR); /* needed in stdio */  \
    }

/*
 * on some systems errno is a macro ... check for it here
 */
#ifndef errno
 extern errno;
#endif

%}
! !

!ExternalStream class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (c) 1988 by Claus Gittinger
	      All Rights Reserved

 This software is furnished under a license and may be used
 only in accordance with the terms of that license and with the
 inclusion of the above copyright notice.   This software may not
 be provided or otherwise made available to, or used by, any
 other person.  No title to or ownership of the software is
 hereby transferred.
"
!

documentation
"
    ExternalStream defines protocol common to Streams which have a file-descriptor and 
    represent some file or communicationChannel of the underlying OperatingSystem.
    ExternalStream is abstract; concrete classes are FileStream, PipeStream etc.

    ExternalStreams can be in two modes: text- (the default) and binary-mode.
    In text-mode, the elements read/written are characters; 
    while in binary-mode the basic elements are bytes which read/write as SmallIntegers 
    in the range 0..255.

    Also, the stream can be either in buffered or unbuffered mode. In buffered mode,
    data is not written until either a cr is written (in text mode) or a synchronizeOutput
    is sent (in both modes).

    The underlying OperatingSystem streams may either be closed explicitely (sending a close)
    or just forgotten - in this case, the garbage collector will eventually collect the
    object AND a close will be performed automatically (but you will NOT know when this 
    happens - so it is recommended, that you close your files when no longer needed).
    Closing is also suggested, since if smalltalk is finished (be it by purpose, or due to
    some crash) the data will not be in the file, if unclosed. 
    All streams understand the close message, so it never hurts to use it (it is defined as 
    a noop in one of the superclasses).

    Most of the methods found here redefine inherited methods for better performance,
    since I/O from/to files should be fast.

    Recovering a snapshot:
    not all streams can be restored to the state they had before - see the implementation of
    reOpen in subclasses for more information.
    For streams sitting on some communication channel (i.e. Pipes and Sockets) you should
    reestablish the stream upon image restart (make someone dependent on ObjectMemory).
    FileStreams are reopened and positioned to their offset they had at snapshot time.
    This may fail, if the file was removed or renamed - or lead to confusion
    if the contents changed in the meantime.
    Therefore, it is a good idea to reopen files and check for these things at restart time.

    Instance variables:

	filePointer     <Integer>       the unix FILE*; somehow mapped to an integer
					(notice: not the fd)
	mode            <Symbol>        #readwrite, #readonly or #writeonly
	buffered        <Boolean>       true, if buffered (i.e. collects characters - does
					not output immediately)
	binary          <Boolean>       true if in binary mode (reads bytes instead of chars)
	useCRLF         <Boolean>       true, if lines should be terminated with crlf instead
					of lf. (i.e. if file is an MSDOS-type file)
	hitEOF          <Boolean>       true, if EOF was reached

	lastErrorNumber <Integer>       the value of errno (only valid right after the error -
					updated with next i/o operation)

    Class variables:
	Lobby           <Registry>      keeps track of used ext-streams (to free up FILE*'s)

	StreamErrorSignal       <Signal> parent of all stream errors (see Stream class)
	InvalidReadSignal       <Signal> raised on read from writeonly stream
	InvalidWriteSignal      <Signal> raised on write to readonly stream 
	InvalidModeSignal       <Signal> raised on text I/O with binary-stream
					 or binary I/O with text-stream
	OpenErrorSignal         <Signal> raised if open fails
	StreamNotOpenSignal     <Signal> raised on I/O with non-open stream

    Additional notes:
      This class is implemented using the underlying stdio-c library package, which
      has both advantages and disadvantages: since it is portable (posix defined), porting
      ST/X to non-Unix machines is simplified. The disadvantage is that the stdio library
      has big problems handling unbounded Streams, since the EOF handling in stdio is
      not prepared for data to arrive after EOF has been reached - time will show, if we need
      a complete rewrite for UnboundedStream ...

      Also, depending on the system, the stdio library behaves infriendly when signals
      occur while reading (for example, timer interrupts) - on real unixes (i.e. BSD) the signal
      is handled transparently - on SYS5.3 (i.e. non unixes :-) the read operation returns
      an error and errno is set to EINTR. Thats what the ugly code around all getc-calls is for.

      Notice that typical stdio's use a single errno global variable to return an error code,
      this was bad design in the stdio lib (right from the very beginning), since its much
      harder to deal with this in the presence of lightweight processes, where errno gets
      overwritten by an I/O operation done in another thread. (stdio should have been written
      to return errno as a negative number ...).
      To deal with this, the scheduler treats errno like a per-thread private variable,
      and saves/restores the errno setting when switching to another thread.
      (Notice that some thread packages do this also, but ST/X's thread implementation
      does not depend on those, but instead uses a portable private package).

      Finally, if an stdio-stream is open for both reading and writing, we have to call
      fseek whenever we are about to read after write and vice versa.
      Two macros (__READING__ and __WRITING__) have been defined to be used before every
      fread/fgetc and fwrite/putc respectively.
"
! !

!ExternalStream class methodsFor:'initialization'!

initialize
    OpenErrorSignal isNil ifTrue:[
	OpenErrorSignal := StreamErrorSignal newSignalMayProceed:true.
	OpenErrorSignal nameClass:self message:#openErrorSignal.
	OpenErrorSignal notifierString:'open error'.

	InvalidReadSignal := ReadErrorSignal newSignalMayProceed:false.
	InvalidReadSignal nameClass:self message:#invalidReadSignal.
	InvalidReadSignal notifierString:'read error'.

	InvalidWriteSignal := WriteErrorSignal newSignalMayProceed:false.
	InvalidWriteSignal nameClass:self message:#invalidWriteSignal.
	InvalidWriteSignal notifierString:'write error'.

	InvalidModeSignal :=  StreamErrorSignal newSignalMayProceed:false.
	InvalidModeSignal nameClass:self message:#invalidModeSignal.
	InvalidModeSignal notifierString:'binary/text mode mismatch'.

	InvalidOperationSignal :=  StreamErrorSignal newSignalMayProceed:false.
	InvalidOperationSignal nameClass:self message:#invalidOperationSignal.
	InvalidOperationSignal notifierString:'unsupported file operation'.

	StreamNotOpenSignal := StreamErrorSignal newSignalMayProceed:false.
	StreamNotOpenSignal nameClass:self message:#streamNotOpenSignal.
	StreamNotOpenSignal notifierString:'stream is not open'.
    ].

    Lobby isNil ifTrue:[
	Lobby := Registry new.

	"want to get informed when returning from snapshot"
	ObjectMemory addDependent:self
    ]
!

reOpenFiles
    "reopen all files (if possible) after a snapShot load"

    Lobby do:[:aFileStream |
	aFileStream reOpen
    ]
!

update:something
    "have to reopen files when returning from snapshot"

    something == #returnFromSnapshot ifTrue:[
	self reOpenFiles
    ]
! !

!ExternalStream class methodsFor:'instance creation'!

forFileDescriptor:aFileDescriptor mode:mode
    |newStream|

    newStream := self basicNew.
    newStream text; buffered:true; useCRLF:false; clearEOF.
    ^ newStream connectTo:aFileDescriptor withMode:mode

    "this will probably fail (15 is a random FD):

     |s|

     s := ExternalStream forFileDescriptor:15 mode:'r'.
     s next.
    "

    "Created: 29.2.1996 / 18:05:00 / cg"
    "Modified: 29.2.1996 / 18:17:07 / cg"
!

forReadWriteToFileDescriptor:aFileDescriptor
    ^ self forFileDescriptor:aFileDescriptor mode:'r+'

    "this will probably fail (15 is a random FD):

     |s|

     s := ExternalStream forReadWriteToFileDescriptor:15.
     s next.
    "

    "Created: 29.2.1996 / 18:15:08 / cg"
    "Modified: 29.2.1996 / 18:16:25 / cg"
!

forReadingFromFileDescriptor:aFileDescriptor
    ^ self forFileDescriptor:aFileDescriptor mode:'r'

    "this will probably fail (15 is a random FD):

     |s|

     s := ExternalStream forReadingFromFileDescriptor:15.
     s next.
    "

    "
     |pipe readFd writeFd rs ws|

     'create OS pipe ...'.

     pipe := OperatingSystem makePipe.
     readFd := pipe at:1.
     writeFd := pipe at:2.

     'connect Smalltalk streams ...'.

     rs := ExternalStream forReadingFromFileDescriptor:readFd.
     ws := ExternalStream forWritingToFileDescriptor:writeFd.

     'read ...'.
     [
	 1 to:10 do:[:i |
	     Transcript showCr:rs nextLine
	 ].
	 rs close.
     ] forkAt:7.

     'write ...'.
     [
	 1 to:10 do:[:i |
	     ws nextPutAll:'hello world '; nextPutAll:i printString; cr
	 ].
	 ws close.
     ] fork.

    "

    "Created: 29.2.1996 / 18:14:24 / cg"
    "Modified: 29.2.1996 / 18:25:02 / cg"
!

forWritingToFileDescriptor:aFileDescriptor
    ^ self forFileDescriptor:aFileDescriptor mode:'w'

    "this will probably fail (15 is a random FD):

     |s|

     s := ExternalStream forWritingToFileDescriptor:15.
     s binary.
     s nextPut:1.
    "

    "Created: 29.2.1996 / 18:14:43 / cg"
    "Modified: 29.2.1996 / 18:15:54 / cg"
!

makePipe
    "return an array with two streams - the first one for reading, the second
     for writing. This is the higher level equivalent of OperatingSystem>>makePipe."

     |pipe rs ws|

     pipe := OperatingSystem makePipe.

     pipe notNil ifTrue:[
	 rs := self forReadingFromFileDescriptor:(pipe at:1).
	 ws := self forWritingToFileDescriptor:(pipe at:2).
	 ^ Array with:rs with:ws
     ].
     ^ nil

    "
     |pipe rs ws|

     pipe := ExternalStream makePipe.
     rs := pipe at:1.
     ws := pipe at:2.

     'read ...'.
     [
	 1 to:10 do:[:i |
	     Transcript showCr:rs nextLine
	 ].
	 rs close.
     ] forkAt:7.

     'write ...'.
     [
	 1 to:10 do:[:i |
	     ws nextPutAll:'hello world '; nextPutAll:i printString; cr
	 ].
	 ws close.
     ] fork.
    "

    "Modified: 29.2.1996 / 18:28:36 / cg"
!

new
    |newStream|

    newStream := self basicNew.
    newStream text; buffered:true; useCRLF:false; clearEOF.
    ^ newStream
! !

!ExternalStream class methodsFor:'Signal constants'!

invalidModeSignal
    "return the signal raised when doing text-I/O with a binary stream
     or binary-I/O with a text stream"

    ^ InvalidModeSignal
!

invalidOperationSignal
    "return the signal raised when an unsupported or invalid
     I/O operation is attempted"

    ^ InvalidOperationSignal
!

invalidReadSignal
    "return the signal raised when reading from writeonly streams"

    ^ InvalidReadSignal
!

invalidWriteSignal
    "return the signal raised when writing to readonly streams"

    ^ InvalidWriteSignal
!

openErrorSignal
    "return the signal raised when a file open failed"

    ^ OpenErrorSignal
!

streamNotOpenSignal
    "return the signal raised on I/O with closed streams"

    ^ StreamNotOpenSignal
! !

!ExternalStream class methodsFor:'error handling'!

lastErrorNumber
    "return the errno of the last error"

    ^ LastErrorNumber

    "
     ExternalStream lastErrorNumber
    "
!

lastErrorString
    "return a message string describing the last error"

    ^ OperatingSystem errorTextForNumber:LastErrorNumber

    "
     ExternalStream lastErrorString
    "
! !

!ExternalStream methodsFor:'accessing'!

binary
    "switch to binary mode - default is text"

    binary := true
!

buffered:aBoolean
    "turn buffering on or off - default is on"

    buffered := aBoolean
!

contents
    "return the contents of the file from the current position up-to
     the end. If the stream is in binary mode, a ByteArray containing
     the byte values is returned.
     In text-mode, a collection of strings, each representing one line,
     is returned."

    |text l chunks sizes chunk byteCount cnt bytes offset|

    binary ifTrue:[
	"adding to a ByteArray produces quadratic time-space
	 behavior - therefore we allocate chunks, and concatenate them
	 at the end."

	chunks := OrderedCollection new.
	sizes := OrderedCollection new.
	byteCount := 0.
	[self atEnd] whileFalse:[
	    chunk := ByteArray uninitializedNew:4096.
	    cnt := self nextBytes:(chunk size) into:chunk.
	    cnt notNil ifTrue:[
		chunks add:chunk.
		sizes add:cnt.
		byteCount := byteCount + cnt
	    ]
	].

	"now, create one big ByteArray"
	bytes := ByteArray uninitializedNew:byteCount.
	offset := 1.
	1 to:chunks size do:[:index |
	    chunk := chunks at:index.
	    cnt := sizes at:index. 
	    bytes replaceFrom:offset to:(offset + cnt - 1) with:chunk.
	    offset := offset + cnt
	].
	^ bytes
    ].

    text := StringCollection new.
    [self atEnd] whileFalse:[
	l := self nextLine.
	l isNil ifTrue:[
	    ^ text
	].
	text add:l
    ].
    ^ text
!

contentsOfEntireFile
    "ST-80 compatibility"

    ^ self contents
!

contentsSpecies
    "return the kind of object to be returned by sub-collection builders
     (such as upTo)"

    binary ifTrue:[
	^ ByteArray
    ].
    ^ String
!

fileDescriptor
    "return the fileDescriptor of the receiver -
     notice: this one returns the underlying OSs fileDescriptor -
     this may not be available on all platforms (i.e. non unix systems)."

%{  /* NOCONTEXT */

    FILE *f;
    OBJ fp;

    if ((fp = __INST(filePointer)) != nil) {
	f = __FILEVal(fp);
	RETURN ( __MKSMALLINT(fileno(f)) );
    }
%}.
    ^ self errorNotOpen
!

fileDescriptor:anInteger withMode:openMode
    "set the filePointer from the receiver based on the fileDescriptor-
     notice: this one is based on the underlying OSs fileDescriptor -
     this may not be available on all platforms (i.e. non unix systems)."

%{  /* NOCONTEXT */

    FILE *f;
    OBJ fp;

    if (__isSmallInteger(anInteger) &&
	__isString(openMode) &&
	(f = fdopen(__intVal(anInteger), __stringVal(openMode))) != 0
    ) {
	__INST(filePointer) = fp = __MKOBJ((int)f); __STORE(self, fp);
	RETURN (self);
    }
%}.
    ^ self primitiveFailed
!

filePointer
    "return the filePointer of the receiver -
     notice: for portability stdio is used; this means you will get
     a FILE * - not a fileDescriptor. 
     (what you really get is a corresponding integer).
     You cannot do much with the returned value 
     - except passing it to a primitive, for example."

    ^ filePointer
!

readonly
    "set access mode to readonly"

    mode := #readonly
!

readwrite
    "set access mode to readwrite"

    mode := #readwrite
!

text
    "switch to text mode - default is text"

    binary := false
!

useCRLF:aBoolean
    "turn on or off CRLF sending (instead of LF only) - default is off"

    useCRLF := aBoolean
!

writeonly
    "set access mode to writeonly"

    mode := #writeonly
! !

!ExternalStream methodsFor:'error handling'!

argumentMustBeCharacter
    "{ Pragma: +optSpace }"

    "report an error, that the argument must be a character"

    ^ self error:'argument must be a character'
!

argumentMustBeInteger
    "{ Pragma: +optSpace }"

    "report an error, that the argument must be an integer"

    ^ self error:'argument must be an integer'
!

argumentMustBeString
    "{ Pragma: +optSpace }"

    "report an error, that the argument must be a string"

    ^ self error:'argument must be a string'
!

errorBinary
    "{ Pragma: +optSpace }"

    "report an error, that the stream is in binary mode"

    ^ InvalidModeSignal
	raiseRequestWith:self
	     errorString:(self class name , ' is in binary mode')
		      in:thisContext sender
!

errorNotBinary
    "{ Pragma: +optSpace }"

    "report an error, that the stream is not in binary mode"

    ^ InvalidModeSignal
	raiseRequestWith:self
	     errorString:(self class name , ' is not in binary mode')
		      in:thisContext sender
!

errorNotBuffered
    "{ Pragma: +optSpace }"

    "report an error, that the stream is not in buffered mode"

    ^ StreamErrorSignal
	raiseRequestWith:self
	     errorString:(self class name , ' is unbuffered - operation not allowed')
		      in:thisContext sender
!

errorNotOpen
    "{ Pragma: +optSpace }"

    "report an error, that the stream has not been opened"

    ^ StreamNotOpenSignal
	raiseRequestWith:self
	     errorString:(self class name , ' not open')
		      in:thisContext sender
!

errorOpen
    "{ Pragma: +optSpace }"

    "report an error, that the stream is already opened"

    ^ OpenErrorSignal
	raiseRequestWith:self
	errorString:(self class name , ' is already open')
		 in:thisContext sender
!

errorReadOnly
    "{ Pragma: +optSpace }"

    "report an error, that the stream is a readOnly stream"

    ^ InvalidWriteSignal
	raiseRequestWith:self
	     errorString:(self class name , ' is readonly')
		      in:thisContext sender
!

errorUnsupportedOperation
    "{ Pragma: +optSpace }"

    "report an error, that some unsupported operation was attempted"

    ^ InvalidOperationSignal
	raiseRequestWith:self
	errorString:'unsupported operation'
		 in:thisContext sender
!

errorWriteOnly
    "{ Pragma: +optSpace }"

    "report an error, that the stream is a writeOnly stream"

    ^ InvalidReadSignal
	raiseRequestWith:self
	     errorString:(self class name , ' is writeonly')
		      in:thisContext sender
!

ioError
    "{ Pragma: +optSpace }"

    "report an error, that some I/O error occured"

    ^ StreamErrorSignal
	raiseRequestWith:self
	     errorString:('I/O error: ' , self lastErrorString)
		      in:thisContext sender
!

lastErrorNumber
    "return the last error"

    ^ lastErrorNumber
!

lastErrorString
    "return a message string describing the last error"

    (lastErrorNumber isNil or:[lastErrorNumber == 0]) ifTrue:[
	^ 'I/O error'
    ].
    ^ OperatingSystem errorTextForNumber:lastErrorNumber
!

openError
    "{ Pragma: +optSpace }"

    "report an error, that the open failed"

    ^ OpenErrorSignal
	raiseRequestWith:self
	     errorString:('error on open: ' , self lastErrorString)
		      in:thisContext sender
!

readError
    "{ Pragma: +optSpace }"

    "report an error, that some read error occured"

    ^ ReadErrorSignal
	raiseRequestWith:self
	     errorString:('read error: ' , self lastErrorString)
		      in:thisContext sender
!

writeError
    "{ Pragma: +optSpace }"

    "report an error, that some write error occured"

    ^ WriteErrorSignal
	raiseRequestWith:self
	     errorString:('write error: ' , self lastErrorString)
		      in:thisContext sender
! !

!ExternalStream methodsFor:'instance release'!

closeFile
    "low level close - may be redefined in subclasses"

%{
    OBJ fp;

    if ((fp = __INST(filePointer)) != nil) {
	__INST(filePointer) = nil;
	__BEGIN_INTERRUPTABLE__
	fclose(__FILEVal(fp));
	__END_INTERRUPTABLE__
    }
%}
!

disposed
    "some Stream has been collected - close the file if not already done"

    self closeFile
!

setFilePointer:anInteger
    filePointer := anInteger
!

shallowCopyForFinalization
    "return a copy for finalization-registration;
     since all we need at finalization time is the fileDescriptor,
     a cheaper copy is possible."

    ^ self class basicNew setFilePointer:filePointer
!

shutDown
    "close the stream - added for protocol compatibility with PipeStream.
     see comment there"

    self closeFile
! !

!ExternalStream methodsFor:'line reading/writing'!

nextLine
    "read the next line (characters up to newline).
     Return a string containing those characters excluding the newline.
     If the previous-to-last character is a cr, this is also removed,
     so its possible to read alien (i.e. ms-dos) text as well.
     The line must be shorter than 16K characters - otherwise its truncated."

%{  /* STACK:17000 */

    FILE *f;
    int len;
    char buffer[16*1024];
    char *rslt, *nextPtr, *limit;
    int fd, ch;
    int _buffered;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__INST(binary) != true) {
	    f = __FILEVal(fp);
	    __BEGIN_INTERRUPTABLE__
	    buffer[0] = 0;

	    _buffered = (__INST(buffered) == true);
	    if (_buffered) {
		__READING__(f);
	    } else {
		fd = fileno(f);
	    }

	    /*
	     * mhmh - the following code looks ok to me,
	     * but seems not to work for sockets
	     */
#ifdef DOES_NOT_WORK
	    if (__INST(mode) == _readwrite)
		fseek(f, 0L, SEEK_CUR); /* needed in stdio */
	    do {
		rslt = fgets(buffer, sizeof(buffer), f);
	    } while ((rslt == NULL) && (errno == EINTR));
#else

	    rslt = nextPtr = buffer;
	    limit = buffer + sizeof(buffer) - 2;

	    for (;;) {
		if (_buffered) {
		    errno = 0;
		    do {
			if (feof(f)) {
			    ch = EOF;
			    break;
			}
			ch = getc(f);
		    } while ((ch < 0) && (errno == EINTR));

		    if (ch == EOF) {
			if (ferror(f)) {
			    if (errno == EINTR) {
				clearerr(f);
				if (! feof(f)) {
				    continue;
				}
			    }
			    __INST(lastErrorNumber) = __MKSMALLINT(errno);
			}
			len = 0;
		    } else {
			len = 1;
			*nextPtr = ch;
		    }
		} else {
		    do {
			errno = 0;
			len = read(fd, nextPtr, 1);
		    } while ((len < 0) && (errno == EINTR));
		}
		if (len <= 0) {
		    if (nextPtr == buffer) {
			rslt = NULL;
		    } else {
			*nextPtr = '\0';
		    }
		    break;
		}
		if (*nextPtr == '\n') {
		    *nextPtr = '\0';
		    break;
		}
		nextPtr++;
		if (nextPtr >= limit) {
		    *nextPtr = '\0';
		    fprintf(stderr, "EXTSTREAM: line truncated in nextLine\n");
		    break;
		}
	    }
#endif
	    __END_INTERRUPTABLE__

	    if (rslt != NULL) {
		/*
		 * that strlen can be avoided and replaced by (nextPtr - buffer)
		 */
		/* len = strlen(buffer); */
		len = nextPtr-buffer;

		if (__INST(position) != nil) {
		    __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + len);
		}
		/* remove EOL character */
		if (len != 0) {
		    if (buffer[len-1] == '\n') {
			buffer[--len] = '\0';
		    }
		    if ((len != 0) && (buffer[len-1] == '\r')) {
			buffer[--len] = '\0';
		    }
		}
		RETURN ( __MKSTRING_L(buffer, len COMMA_CON) );
	    }
	    if (ferror(f) && (errno != 0)) {
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    } else {
		__INST(hitEOF) = true;
		RETURN ( nil );
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    self errorBinary
!

nextPutLine:aString
    "write the characters in aString and append a newline"

%{
    FILE *f;
    int len, cnt, len1;
    OBJ pos, fp;
    char *cp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil) 
     && (__INST(mode) != @symbol(readonly))) {
	if (__INST(binary) != true) {
	    if (__isString(aString)) {
		f = __FILEVal(fp);
		cp = (char *) __stringVal(aString);
		len = __stringSize(aString);

		__BEGIN_INTERRUPTABLE__

		if (__INST(buffered) == true) {
		    __WRITING__(f)
		    cnt = fwrite(cp, 1, len, f);
		} else {
		    do {
			cnt = write(fileno(f), cp, len);
		    } while ((cnt < 0) && (errno == EINTR));
		}

		if (cnt == len) {
		    len1 = len;

		    if (__INST(useCRLF) == true) {
			cp = "\r\n"; len = 2;
		    } else {
			cp = "\n"; len = 1;
		    }
		    if (__INST(buffered) == true) {
			cnt = fwrite(cp, 1, len, f);
		    } else {
			do {
			    cnt = write(fileno(f), cp, len);
			} while ((cnt < 0) && (errno == EINTR));
		    }

		    if (cnt > 0) {
			pos = __INST(position);
			if (pos != nil) {
			    __INST(position) = __MKSMALLINT(__intVal(pos)+len1+cnt);
			}
			__END_INTERRUPTABLE__

			RETURN ( self );
		    }
		}

		__END_INTERRUPTABLE__
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    binary ifTrue:[^ self errorBinary].

    super nextPutAll:aString.
    self cr.
!

nextPutLinesFrom:aStream upToLineStartingWith:aStringOrNil
    "read from aStream up to and including a line starting with aStringOrNil
     and append it to self. 
     Can be used to copy/create large files or copy from a pipe/socket.

     If aStringOrNil is nil or not matched, copy preceeds to the end.
     (this allows for example to read a Socket and transfer the data quickly
      into a file - without creating zillions of temporary strings)"

    |srcFilePointer readError|

    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    srcFilePointer := aStream filePointer.
    srcFilePointer isNil ifTrue:[^ aStream errorNotOpen].

%{  /* STACK:2000 */

    FILE *dst, *src;
    char *matchString;
    int matchLen = 0;
    char buffer[1024];

    __INST(lastErrorNumber) = nil;
    if (__isSmallInteger(srcFilePointer)) {
	if ((aStringOrNil == nil) || __isString(aStringOrNil)) {
	    if (aStringOrNil != nil) {
		matchString = (char *) __stringVal(aStringOrNil);
		matchLen = __stringSize(aStringOrNil);
	    }
	    dst = __FILEVal(__INST(filePointer));
	    src = __FILEVal(srcFilePointer);
	    __BEGIN_INTERRUPTABLE__
	    errno = 0;

	    __WRITING__(dst)

	    for (;;) {
		if (fgets(buffer, sizeof(buffer)-1, src) == NULL) {
		    if (ferror(src)) {
			readError = __MKSMALLINT(errno);
			__END_INTERRUPTABLE__
			goto err;
		    }
		    break;
		}
		if (fputs(buffer, dst) == EOF) {
		    if (ferror(dst)) {
			__INST(lastErrorNumber) = __MKSMALLINT(errno);
			__END_INTERRUPTABLE__
			goto err;
		    }
		    break;
		}
#ifndef OLD
		if (__INST(buffered) == false) {
		    fflush(dst);
		}
#endif
		if (matchLen) {
		    if (strncmp(matchString, buffer, matchLen) == 0) 
			break;
		}
	    }
	    __END_INTERRUPTABLE__
	    __INST(position) = nil;
	    RETURN (self);
	}
    }
err: ;
%}.
    readError ifTrue:[
	aStream setLastErrorNumber:readError.
	^ aStream readError
    ].
    lastErrorNumber notNil ifTrue:[^ self writeError].
    buffered ifFalse:[^ self errorNotBuffered].
    "
     argument error
    "
    ^ self primitiveFailed
!

peekForLineStartingWith:aString
    "read ahead for next line starting with aString;
     return the line-string if found, or nil if EOF is encountered.
     If matched, not advance position behond that line
     i.e. nextLine will read the matched line.
     If not matched, reposition to original position for firther reading."

    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    binary ifTrue:[^ self errorBinary].

%{  /* STACK: 2000 */
    FILE *f;
    int l;
    char buffer[1024];
    char *cp;
    char *matchString;
    int  firstpos = -1, lastpos;

    __INST(lastErrorNumber) = nil;
    if (__isString(aString)) {
	matchString = (char *) __stringVal(aString);
	l = __stringSize(aString);

	f = __FILEVal(__INST(filePointer));
	__READING__(f)

	for (;;) {
	    lastpos = ftell(f);
	    if (firstpos == -1) firstpos = lastpos;

	    __BEGIN_INTERRUPTABLE__
	    do {
		cp = fgets(buffer, sizeof(buffer)-1, f);
	    } while ((cp == NULL) && (errno == EINTR));
	    buffer[sizeof(buffer)-1] = '\0';
	    __END_INTERRUPTABLE__

	    if (cp == NULL) {
		if (ferror(f)) {
		    __INST(lastErrorNumber) = __MKSMALLINT(errno);
		    goto err;
		} else {
		    fseek(f, firstpos, SEEK_SET);
		    RETURN (nil);
		}
	    }
	    if (strncmp(cp, matchString, l) == 0) {
		fseek(f, lastpos, SEEK_SET);
		break;
	    }
	}
	/* remove EOL character */
	cp = buffer;
	while (*cp && (*cp != '\n')) cp++;
	*cp = '\0';
	RETURN ( __MKSTRING(buffer COMMA_CON) );
    }
err: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    ^ self argumentMustBeString
!

peekForLineStartingWithAny:aCollectionOfStrings
    "read ahead for next line starting with any of aCollectionOfStrings;
     return the index in aCollection if found, nil otherwise..
     If no match, do not change position; otherwise advance right before the
     matched line so that nextLine will return this line."

    |line startPos linePos index|

    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    binary ifTrue:[^ self errorBinary].

    startPos := self position.
    [self atEnd] whileFalse:[
	linePos := self position.
	line := self nextLine.
	line notNil ifTrue:[
	    index := 1.
	    aCollectionOfStrings do:[:prefix |
		(line startsWith:prefix) ifTrue:[
		    self position:linePos.
		    ^ index
		].
		index := index + 1
	    ]
	]
    ].
    self position:startPos.
    ^ nil
! !

!ExternalStream methodsFor:'misc functions'!

async:aBoolean
    "set/clear the async attribute - if set, the availability of data on 
     the receiver will trigger an ioInterrupt.
     If cleared (which is the default) no special notification is made.
     Notice: not every OS supports this - check with OS>>supportsIOInterrupts before"

    |fd|

    filePointer isNil ifTrue:[^ self errorNotOpen].
    fd := self fileDescriptor.
    aBoolean ifTrue:[
	^ OperatingSystem enableIOInterruptsOn:fd
    ].
    ^ OperatingSystem disableIOInterruptsOn:fd
!

backStep
    "step back one element -
     redefined, since position is redefined here"

    self position:(self position - 1)
!

blocking:aBoolean
    "set/clear the blocking attribute - if set (which is the default)
     a read (using next) on the receiver will block until data is available.
     If cleared, a read operation will immediately return with a value of
     nil."

    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ OperatingSystem setBlocking:aBoolean on:(self fileDescriptor)
!

close
    "close the stream - tell operating system"

    filePointer isNil ifTrue:[^ self].
    Lobby unregister:self.
    self closeFile.
    filePointer := nil
!

create
    "create the stream
     - this must be redefined in subclass"

    ^ self subclassResponsibility
!

ioctl:ioctlNumber
    "to provide a simple ioctl facility - an ioctl is performed
     on the underlying file; no arguments are passed."

%{
#ifndef MSDOS_LIKE
    FILE *f;
    int ret, ioNum, ioArg;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if ((fp = __INST(filePointer)) != nil) {
	if (__isSmallInteger(ioctlNumber)) {
	    ioNum = __intVal(ioctlNumber);
	    f = __FILEVal(fp);

	    __BEGIN_INTERRUPTABLE__
	    do {
		ret = ioctl(fileno(f), ioNum);
	    } while ((ret < 0) && (errno == EINTR));
	    __END_INTERRUPTABLE__

	    if (ret >= 0) {
		RETURN ( __MKSMALLINT(ret) );
	    }
	    __INST(position) = nil;
	    __INST(lastErrorNumber) = __MKSMALLINT(errno);
	}
    }
#endif
%}.
    lastErrorNumber notNil ifTrue:[^ self ioError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    "
     ioctl-number is not an integer
     or the system does not support ioctl (MSDOS)
    "
    ^ self primitiveFailed
!

ioctl:ioctlNumber with:arg
    "to provide a simple ioctl facility - an ioctl is performed
     on the underlying file; the argument is passed as argument.
     If the argument is a number, its directly passed; if its a
     kind of ByteArray (ByteArray, String or Structure) a pointer to
     the data is passed. This allows performing most ioctls - however,
     it might be tricky to setup the buffer."

%{
#ifndef MSDOS_LIKE
    FILE *f;
    int ret, ioNum;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if ((fp = __INST(filePointer)) != nil) {
	if (__isSmallInteger(ioctlNumber) 
	 && (__isSmallInteger(arg) || __isBytes(arg))) {
	    f = __FILEVal(fp);
	    ioNum = __intVal(ioctlNumber);

	    __BEGIN_INTERRUPTABLE__
	    do {
		if (__isSmallInteger(arg)) {
		    ret = ioctl(fileno(f), ioNum, __intVal(arg));
		} else {
		    ret = ioctl(fileno(f), ioNum, __ByteArrayInstPtr(arg)->ba_element);
		}
	    } while ((ret < 0) && (errno == EINTR));
	    __END_INTERRUPTABLE__

	    if (ret >= 0) {
		RETURN ( __MKSMALLINT(ret) );
	    }
	    __INST(position) = nil;
	    __INST(lastErrorNumber) = __MKSMALLINT(errno);
	}
    }
#endif
%}.
    lastErrorNumber notNil ifTrue:[^ self ioError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    "
     ioctl-number is not an integer or argument is not byteArray-like
     or the system does not support ioctl (MSDOS)
    "
    ^ self primitiveFailed
!

open
    "open the stream
     - this must be redefined in subclass"

    ^ self subclassResponsibility
!

position
    "return the position
     - this must be redefined in subclass"

    ^ self subclassResponsibility
!

position:anInteger
    "set the position
     - this must be redefined in subclass"

    ^ self subclassResponsibility
!

reset
    "set the read position to the beginning of the collection"

    self position:"0" 1
!

setToEnd
    "redefined since it must be implemented differently"

    ^ self subclassResponsibility
!

truncateTo:newSize
    "truncate the underlying OS file to newSize.
     Warning: this may not be implemented on all platforms."

%{
#ifdef HAS_FTRUNCATE
    FILE *f;
    OBJ fp;

    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))) {
	if (__isSmallInteger(newSize)) {
	    f = __FILEVal(fp);

	    if (__INST(buffered) == true) {
		__READING__(f)
		fflush(f);
		fseek(f, 0L, SEEK_END); /* needed in stdio */
	    }
	    ftruncate(fileno(f), __intVal(newSize));
	    RETURN (self);
	}
    }
#endif
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    ^ self errorUnsupportedOperation

    "
     |s|

     s := 'test' asFilename writeStream.
     s next:1000 put:$a.
     s truncateTo:100.
     s close.

     ('test' asFilename fileSize) printNL
    "
! !

!ExternalStream methodsFor:'non homogenous reading'!

nextByte
    "read the next byte and return it as an Integer; return nil on error.
     This is allowed in both text and binary modes, always returning the
     bytes binary value as an integer in 0..255."

%{
    FILE *f;
    unsigned char byte;
    int cnt;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	f = __FILEVal(fp);

	if (__INST(buffered) == true) {
	    __READING__(f)
	}

	__BEGIN_INTERRUPTABLE__
	do {
	    if (__INST(buffered) == false) {
		cnt = read(fileno(f), &byte, 1);
	    } else {
		cnt = fread(&byte, 1, 1, f);
	    }
	} while ((cnt < 0) && (errno == EINTR));
	__END_INTERRUPTABLE__

	if (cnt == 1) {
	    if (__INST(position) != nil)
		__INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 1);
	    RETURN ( __MKSMALLINT(byte) );
	}
	if (cnt == 0) {
	    __INST(hitEOF) = true;
/*
	    if (errno == EWOULDBLOCK) {
		RETURN (nil);
	    }
*/
	}
	__INST(position) = nil;
	__INST(lastErrorNumber) = __MKSMALLINT(errno);
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ self errorWriteOnly
!

nextBytes:count into:anObject
    "read the next count bytes into an object and return the number of
     bytes read. On EOF, 0 is returned.
     If the receiver is some socket/pipe-like stream, an exception
     is raised if the connection is broken.

     The object must have non-pointer indexed instvars (i.e. it must be 
     a ByteArray, String, Float- or DoubleArray).
     If anObject is a string or byteArray and reused, this provides the
     fastest possible physical I/O (since no new objects are allocated).

     Use with care - non object oriented i/o.
     Warning: in general, you cannot use this method to pass data from other 
     architectures since it does not care for byte order or float representation."

    ^ self nextBytes:count into:anObject startingAt:1
!

nextBytes:count into:anObject startingAt:start
    "read the next count bytes into an object and return the number of
     bytes read or 0 on EOF. 
     If the receiver is some socket/pipe-like stream, an exception
     is raised if the connection is broken.
     Notice, that in contrast to other methods
     here, this does NOT return nil on EOF, but the actual count.
     Thus allowing read of partial blocks.

     The object must have non-pointer indexed instvars 
     (i.e. it must be a ByteArray, String, Float- or DoubleArray).
     If anObject is a string or byteArray and reused, this provides the
     fastest possible physical I/O (since no new objects are allocated).

     Use with care - non object oriented I/O.
     Warning: in general, you cannot use this method to pass data from other 
     architectures since it does not care for byte order or float representation."

%{
    FILE *f;
    int cnt, offs, ret;
    int objSize, nInstVars, nInstBytes;
    char *cp;
    OBJ pos, fp, oClass;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__bothSmallInteger(count, start)) {
	    f = __FILEVal(fp);

	    oClass = __Class(anObject);
	    switch (__intVal(__ClassInstPtr(oClass)->c_flags) & ARRAYMASK) {
		case BYTEARRAY:
		case WORDARRAY:
		case LONGARRAY:
		case FLOATARRAY:
		case DOUBLEARRAY:
		    break;
		default:
		    goto bad;
	    }
	    cnt = __intVal(count);
	    offs = __intVal(start) - 1;
	    nInstVars = __intVal(__ClassInstPtr(oClass)->c_ninstvars);
	    nInstBytes = OHDR_SIZE + __OBJS2BYTES__(nInstVars);
	    objSize = __Size(anObject) - nInstBytes;
	    if ((offs >= 0) && (cnt >= 0) && (objSize >= (cnt + offs))) {
		/* 
		 * mhmh - since we are interruptable, anObject may move.
		 * therefore, fetch the cp-pointer within the loop
		 */
		if (__INST(buffered) == true) {
		    __READING__(f)
		}

		for (;;) {
		    errno = 0;
		    /*
		     * because we are interruptable, refetch pointer
		     */
		    cp = (char *)__InstPtr(anObject) + nInstBytes + offs;
		    if (__INST(buffered) == false) {
			ret = read(fileno(f), cp, cnt);
		    } else {
			if (feof(f)) {
			    ret = 0;
			    break;
			}
			ret = fread(cp, 1, cnt, f);
		    }
		    if (ret < 0) {
			if (errno == EINTR)  {
			    __HANDLE_INTERRUPTS__
			    continue;
			}
			else
			    break;
		    }   
		    cnt -= ret;
		    if (cnt == 0 || ret == 0)
			break;
		    offs += ret;
		    __HANDLE_INTERRUPTS__
		} 

		cnt = __intVal(count) - cnt;

		if (cnt > 0) {
		    pos = __INST(position);
		    if (pos != nil) {
			__INST(position) = __MKSMALLINT(__intVal(pos) + cnt);
		    }
		    RETURN (__MKSMALLINT(cnt));
		}
		if (cnt == 0) { 
		    __INST(hitEOF) = true;
		    RETURN (__MKSMALLINT(cnt));
		}

		__INST(position) = nil;
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    }
	}
    }
bad: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    "
     count not integer or arg not bit-like (String, ByteArray etc)
    "
    ^ self primitiveFailed
!

nextBytesInto:anObject
    "read bytes into an object, regardless of binary/text mode.
     The number of bytes to read is defined by the objects size.
     Return the number of bytes read. On EOF, 0 is returned.
     If the receiver is some socket/pipe-like stream, an exception
     is raised if the connection is broken.

     The object to read into must have non-pointer indexed instvars 
     (i.e. it must be a ByteArray, String, Float- or DoubleArray).     
     If anObject is a string or byteArray and reused, this provides the
     fastest possible physical I/O (since no new objects are allocated).

     Use with care - non object oriented i/o.
     Warning: in general, you cannot use this method to pass data from other 
     architectures since it does not care for byte order or float representation."

    ^ self nextBytes:(anObject size) into:anObject startingAt:1

    " to read 100 bytes from a stream:
    
     |b aStream|

     aStream := 'smalltalk.rc' asFilename readStream.
     b := ByteArray new:100.
     aStream nextBytesInto:b.
     aStream close.
     b inspect
    "

    "
     |s aStream|
     aStream := 'smalltalk.rc' asFilename readStream.
     s := String new:100.
     aStream nextBytesInto:s.
     aStream close.
     s inspect
    "
!

nextLong
    "Read four bytes (msb-first) and return the value as a 32-bit signed Integer.
     The returned value may be a LargeInteger.
     (msb-first for compatibility with other smalltalks)"

    ^ self nextUnsignedLongMSB:true
!

nextLongMSB:msbFlag
    "Read four bytes and return the value as a 32-bit signed Integer, 
     which may be a LargeInteger.
     If msbFlag is true, value is read with most-significant byte first, 
     otherwise least-significant byte comes first.
     A nil is returned, if EOF is hit before all 4 bytes have been read.
     Works in both binary and text modes."

%{
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
        FILE *f;
        int ret;
        int value;
        int cnt = 4, offs = 0;
        char buffer[4];

        f = __FILEVal(fp);
        for (;;) {
            errno = 0;
            if (__INST(buffered) == false) {
                ret = read(fileno(f), buffer+offs, cnt);
            } else {
                if (feof(f)) {
                    ret = 0;
                    break;
                }
                ret = fread(buffer+offs, 1, cnt, f);
            }
            if (ret < 0) {
                if (errno == EINTR)  {
                    __HANDLE_INTERRUPTS__
                    continue;
                }
                else
                    break;
            }   
            cnt -= ret;
            if (cnt == 0 || ret == 0)
                break;
            offs += ret;
            __HANDLE_INTERRUPTS__
        }

        if (cnt == 0) {
            if (__INST(position) != nil) {
                __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 4);
            }
            if (msbFlag == true) {
                value = (buffer[0] & 0xFF);
                value = (value << 8) | (buffer[1] & 0xFF);
                value = (value << 8) | (buffer[2] & 0xFF);
                value = (value << 8) | (buffer[3] & 0xFF);
            } else {
                value = (buffer[3] & 0xFF);
                value = (value << 8) | (buffer[2] & 0xFF);
                value = (value << 8) | (buffer[1] & 0xFF);
                value = (value << 8) | (buffer[0] & 0xFF);
            }
            if ((value >= _MIN_INT) && (value <= _MAX_INT)) {
                RETURN ( __MKSMALLINT(value));
            }
            RETURN ( __MKLARGEINT(value) );
        }

        if ((__INST(buffered) == false && ret < 0) || (ferror(f) && (errno != 0))) {
            __INST(position) = nil;
            __INST(lastErrorNumber) = __MKSMALLINT(errno);
        } else {
            __INST(hitEOF) = true;
            RETURN (nil);
        }
    }
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    ^ self readError.

!

nextShortMSB:msbFlag
    "Read two bytes and return the value as a 16-bit signed Integer.
     If msbFlag is true, value is read with most-significant byte first, 
     otherwise least-significant byte comes first.
     A nil is returned if EOF is reached (also when EOF is hit after the first byte).
     Works in both binary and text modes."

%{
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
        FILE *f;
        int ret;
        short value;
        int cnt = 2, offs = 0;
        char buffer[2];

        f = __FILEVal(fp);
        for (;;) {
            errno = 0;
            if (__INST(buffered) == false) {
                ret = read(fileno(f), buffer+offs, cnt);
            } else {
                if (feof(f)) {
                    ret = 0;
                    break;
                }
                ret = fread(buffer+offs, 1, cnt, f);
            }
            if (ret < 0) {
                if (errno == EINTR)  {
                    __HANDLE_INTERRUPTS__
                    continue;
                }
                else
                    break;
            }   
            cnt -= ret;
            if (cnt == 0 || ret == 0)
                break;
            offs += ret;
            __HANDLE_INTERRUPTS__
        }

        if (cnt == 0) {
            if (__INST(position) != nil) {
                __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 2);
            }
            if (msbFlag == true) {
                value = ((buffer[0] & 0xFF) << 8) | (buffer[1] & 0xFF);
            } else {
                value = ((buffer[1] & 0xFF) << 8) | (buffer[0] & 0xFF);
            }
            RETURN (__MKSMALLINT(value));
        }

        if ((__INST(buffered) == false && ret < 0) || (ferror(f) && (errno != 0))) {
            __INST(position) = nil;
            __INST(lastErrorNumber) = __MKSMALLINT(errno);
        } else {
            __INST(hitEOF) = true;
            RETURN (nil);
        }
    }
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    ^ self readError.
!

nextUnsignedLongMSB:msbFlag
    "Read four bytes and return the value as a 32-bit unsigned Integer, which may be
     a LargeInteger.
     If msbFlag is true, value is read with most-significant byte first, otherwise
     least-significant byte comes first.
     A nil is returned, if endOfFile occurs before all 4 bytes have been read.
     Works in both binary and text modes."

%{
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
        FILE *f;
        int ret;
        unsigned int value;
        int cnt = 4, offs = 0;
        char buffer[4];

        f = __FILEVal(fp);
        for (;;) {
            errno = 0;
            if (__INST(buffered) == false) {
                ret = read(fileno(f), buffer+offs, cnt);
            } else {
                if (feof(f)) {
                    ret = 0;
                    break;
                }
                ret = fread(buffer+offs, 1, cnt, f);
            }
            if (ret < 0) {
                if (errno == EINTR)  {
                    __HANDLE_INTERRUPTS__
                    continue;
                }
                else
                    break;
            }   
            cnt -= ret;
            if (cnt == 0 || ret == 0)
                break;
            offs += ret;
            __HANDLE_INTERRUPTS__
        }

        if (cnt == 0) {
            if (__INST(position) != nil) {
                __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 4);
            }
            if (msbFlag == true) {
                value = (buffer[0] & 0xFF);
                value = (value << 8) | (buffer[1] & 0xFF);
                value = (value << 8) | (buffer[2] & 0xFF);
                value = (value << 8) | (buffer[3] & 0xFF);
            } else {
                value = (buffer[3] & 0xFF);
                value = (value << 8) | (buffer[2] & 0xFF);
                value = (value << 8) | (buffer[1] & 0xFF);
                value = (value << 8) | (buffer[0] & 0xFF);
            }
            if (value <= _MAX_INT) {
                RETURN ( __MKSMALLINT(value));
            }
            RETURN ( __MKULARGEINT(value) );
        }

        if ((__INST(buffered) == false && ret < 0) || (ferror(f) && (errno != 0))) {
            __INST(position) = nil;
            __INST(lastErrorNumber) = __MKSMALLINT(errno);
        } else {
            __INST(hitEOF) = true;
            RETURN (nil);
        }
    }
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    ^ self readError.
!

nextUnsignedShortMSB:msbFlag
    "Read two bytes and return the value as a 16-bit unsigned Integer.
     If msbFlag is true, value is read with most-significant byte first, 
     otherwise least-significant byte comes first.
     A nil is returned if EOF is reached (also when EOF is hit after the first byte).
     Works in both binary and text modes."

%{
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
        FILE *f;
        int ret;
        unsigned int value;
        int cnt = 2, offs = 0;
        char buffer[2];

        f = __FILEVal(fp);
        for (;;) {
            errno = 0;
            if (__INST(buffered) == false) {
                ret = read(fileno(f), buffer+offs, cnt);
            } else {
                if (feof(f)) {
                    ret = 0;
                    break;
                }
                ret = fread(buffer+offs, 1, cnt, f);
            }
            if (ret < 0) {
                if (errno == EINTR)  {
                    __HANDLE_INTERRUPTS__
                    continue;
                }
                else
                    break;
            }   
            cnt -= ret;
            if (cnt == 0 || ret == 0)
                break;
            offs += ret;
            __HANDLE_INTERRUPTS__
        }

        if (cnt == 0) {
            if (__INST(position) != nil) {
                __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 2);
            }
            if (msbFlag == true) {
                value = ((buffer[0] & 0xFF) << 8) | (buffer[1] & 0xFF);
            } else {
                value = ((buffer[1] & 0xFF) << 8) | (buffer[0] & 0xFF);
            }
            RETURN (__MKSMALLINT(value));
        }

        if ((__INST(buffered) == false && ret < 0) || (ferror(f) && (errno != 0))) {
            __INST(position) = nil;
            __INST(lastErrorNumber) = __MKSMALLINT(errno);
        } else {
            __INST(hitEOF) = true;
            RETURN (nil);
        }
    }
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    ^ self readError.
!

nextWord
    "in text-mode:
	 read the alphaNumeric next word (i.e. up to non letter-or-digit).
	 return a string containing those characters.
     in binary-mode:
	 read two bytes (msb-first) and return the value as a 16-bit 
	 unsigned Integer (for compatibility with other smalltalks)"

    binary ifTrue:[
	^ self nextUnsignedShortMSB:true
    ].
    ^ self nextAlphaNumericWord
! !

!ExternalStream methodsFor:'non homogenous writing'!

nextPutByte:aByteValue
    "write a byte.
     Works in both binary and text modes."

%{
    FILE *f;
    char c;
    OBJ pos, fp;
    int cnt;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))) {
	if (__isSmallInteger(aByteValue)) {
	    c = __intVal(aByteValue);
	    f = __FILEVal(fp);
	    __BEGIN_INTERRUPTABLE__
/*
 *#ifdef OLD
 *          if (__INST(buffered) == false) {
 *              cnt = write(fileno(f), &c, 1);
 *          } else 
 *#endif
 *          {
 *              __WRITING__(f)
 *              cnt = fwrite(&c, 1, 1, f);
 *#ifndef OLD
 *              if (__INST(buffered) == false) {
 *                  fflush(f);
 *              }
 *#endif
 *          }
 */
	    if (__INST(buffered) == true) {
		__WRITING__(f)
		cnt = fwrite(&c, 1, 1, f);
	    } else {
		do {
		    cnt = write(fileno(f), &c, 1);
		} while ((cnt < 0) && (errno == EINTR));
	    }
	    __END_INTERRUPTABLE__

	    if (cnt == 1) {
		pos = __INST(position);
		if (pos != nil)
		    __INST(position) = __MKSMALLINT(__intVal(pos) + 1);
		RETURN (self);
	    }
	    if (cnt < 0) {
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    }
	}
    }
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    ^ self writeError.
!

nextPutBytes:count from:anObject
    "write count bytes from an object.
     Return the number of bytes written or nil on error.
     The object must have non-pointer indexed instvars 
     (i.e. be a ByteArray, String, Float- or DoubleArray).     
     Use with care - non object oriented i/o.
     Warning: in general, you cannot use this method to pass data to other 
     architectures since it does not care for byte order or float representation."

    ^ self nextPutBytes:count from:anObject startingAt:1
!

nextPutBytes:count from:anObject startingAt:start
    "write count bytes from an object starting at index start.
     return the number of bytes written - which could be 0.
     The object must have non-pointer indexed instvars 
     (i.e. be a ByteArray, String, Float- or DoubleArray).     
     Use with care - non object oriented i/o.
     Warning: in general, you cannot use this method to pass data to other 
     architectures since it does not care for byte order or float representation."

%{
    FILE *f;
    int cnt, offs, ret;
    int objSize, nInstVars, nInstBytes;
    char *cp;
    OBJ oClass, pos, fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))) {
	if (__bothSmallInteger(count, start)) {
	    oClass = __Class(anObject);
	    switch (__intVal(__ClassInstPtr(oClass)->c_flags) & ARRAYMASK) {
		case BYTEARRAY:
		case WORDARRAY:
		case LONGARRAY:
		case FLOATARRAY:
		case DOUBLEARRAY:
		    break;
		default:
		    goto bad;
	    }
	    cnt = __intVal(count);
	    offs = __intVal(start) - 1;
	    f = __FILEVal(fp);

	    nInstVars = __intVal(__ClassInstPtr(oClass)->c_ninstvars);
	    nInstBytes = OHDR_SIZE + __OBJS2BYTES__(nInstVars);
	    objSize = __Size(anObject) - nInstBytes;
	    if ( (offs >= 0) && (cnt >= 0) && (objSize >= (cnt + offs)) ) {
		cp = (char *)__InstPtr(anObject) + nInstBytes + offs;

		if (__INST(buffered) == true) {
		    /* do not handle interrupts here.
		     * fwrite is not ineterruot capable!
		     */
		    __WRITING__(f)
		    cnt = fwrite(cp, 1, cnt, f);
		} else {
		    for (;;) {
			cp = (char *)__InstPtr(anObject) + nInstBytes + offs;
			ret = write(fileno(f), cp, cnt);
			if (ret < 0) {
			    if (errno == EINTR) {
				__HANDLE_INTERRUPTS__
				continue;
			    } else
				break;
			}
			if (ret == cnt) {
			    break;
			}
			offs += ret;
			cnt -= ret;
			__HANDLE_INTERRUPTS__
		    }
		    cnt = __intVal(count) - cnt;
		}

		if (cnt >= 0) {
		    pos = __INST(position);
		    if (pos != nil)
			__INST(position) = __MKSMALLINT(__intVal(pos) + cnt);
		    RETURN ( __MKSMALLINT(cnt) );
		}
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    }
	}
    }
bad: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    ^ self primitiveFailed
!

nextPutBytesFrom:anObject
    "write bytes from an object; the number of bytes is defined by
     the objects size.
     Return the number of bytes written or nil on error.
     The object must have non-pointer indexed instvars 
     (i.e. be a ByteArray, String, Float- or DoubleArray).     
     Use with care - non object oriented i/o.
     Warning: in general, you cannot use this method to pass data to other 
     architectures since it does not care for byte order or float representation."

    ^ self nextPutBytes:(anObject size) from:anObject startingAt:1
!

nextPutLong:aNumber MSB:msbFlag
    "Write the argument, aNumber as a long (four bytes). If msbFlag is
     true, data is written most-significant byte first; otherwise least
     first.
     Works in both binary and text modes."

%{
    int num;
    char bytes[4];
    FILE *f;
    int cnt;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))
     && __isSmallInteger(aNumber)) {
	num = __intVal(aNumber);
	if (msbFlag == true) {
	    bytes[0] = (num >> 24) & 0xFF;
	    bytes[1] = (num >> 16) & 0xFF;
	    bytes[2] = (num >> 8) & 0xFF;
	    bytes[3] = num & 0xFF;
	} else {
	    bytes[3] = (num >> 24) & 0xFF;
	    bytes[2] = (num >> 16) & 0xFF;
	    bytes[1] = (num >> 8) & 0xFF;
	    bytes[0] = num & 0xFF;
	}

	f = __FILEVal(fp);
	__BEGIN_INTERRUPTABLE__

	if (__INST(buffered) == true) {
	    __WRITING__(f)
	    cnt = fwrite(bytes, 1, 4, f);
	} else {
	    do {
		cnt = write(fileno(f), bytes, 4);
	    } while ((cnt < 0) && (errno == EINTR));
	}

	__END_INTERRUPTABLE__

	if (cnt == 4) {
	    if (__INST(position) != nil) {
		__INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 4);
	    }
	    RETURN ( self );
	}
	__INST(lastErrorNumber) = __MKSMALLINT(errno);
    }
%}.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    lastErrorNumber notNil ifTrue:[^ self writeError].

    aNumber isInteger ifTrue:[
	msbFlag ifTrue:[
	    "high word first"
	    (self nextPutShort:(aNumber // 16r10000) MSB:true) isNil ifTrue:[^ nil].
	    ^ self nextPutShort:(aNumber \\ 16r10000) MSB:true
	].
	"low word first"
	(self nextPutShort:(aNumber \\ 16r10000) MSB:false) isNil ifTrue:[^ nil].
	^ self nextPutShort:(aNumber // 16r10000) MSB:false.
    ].
    self argumentMustBeInteger
!

nextPutShort:aNumber MSB:msbFlag
    "Write the argument, aNumber as a short (two bytes). If msbFlag is
     true, data is written most-significant byte first; otherwise least
     first.
     Works in both binary and text modes."

%{
    int num;
    char bytes[2];
    FILE *f;
    int cnt;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))
     && __isSmallInteger(aNumber)) {
        num = __intVal(aNumber);
        if (msbFlag == true) {
            bytes[0] = (num >> 8) & 0xFF;
            bytes[1] = num & 0xFF;
        } else {
            bytes[1] = (num >> 8) & 0xFF;
            bytes[0] = num & 0xFF;
        }

        f = __FILEVal(fp);
        __BEGIN_INTERRUPTABLE__

        if (__INST(buffered) == true) {
            __WRITING__(f)
            cnt = fwrite(bytes, 1, 2, f);
        } else {
            int offs = 0;
            do {
                cnt = write(fileno(f), bytes+offs, 2-offs);
                if (cnt > 0)
                    offs += cnt;
            } while (((cnt > 0) && (offs < 2)) || 
                     ((cnt < 0) && (errno == EINTR)));
            cnt = offs;
        }

        __END_INTERRUPTABLE__

        if (cnt == 2) {
            if (__INST(position) != nil) {
                __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + 2);
            }
            RETURN ( self );
        }
        __INST(lastErrorNumber) = __MKSMALLINT(errno);
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    self argumentMustBeInteger
! !

!ExternalStream methodsFor:'private'!

clearEOF
    hitEOF := false
!

connectTo:aFileDescriptor withMode:openmode
    "connect a fileDescriptor; openmode is the string defining the way to open.
     This can be used to connect an extrnally provided fileDescriptor (from
     primitive code) or a pipeFileDescriptor (as returned by makePipe) to
     a Stream object. 
     The openMode ('r', 'w' etc.) must match the mode in which
     the fileDescriptor was originally opened (otherwise i/o errors will be reported later)."

    |retVal|

    filePointer notNil ifTrue:[^ self errorOpen].
%{
    FILE *f;
    OBJ fp;

    if (__isSmallInteger(aFileDescriptor) 
     && (__qClass(openmode)== @global(String))) {
	f = (FILE *) fdopen(__intVal(aFileDescriptor), (char *)__stringVal(openmode));
	if (f == NULL) {
	    __INST(lastErrorNumber) = __MKSMALLINT(errno);
	    __INST(position) = nil;
	} else {
	    __INST(filePointer) = fp = __MKOBJ((int)f); __STORE(self, fp);
	    __INST(position) = __MKSMALLINT(1);
	    retVal = self;
	}
    }
%}.
    retVal notNil ifTrue:[
	buffered := true.       "default is buffered"
	Lobby register:self
    ].
    lastErrorNumber notNil ifTrue:[
	"
	 the open failed for some reason ...
	"
	^ self openError
    ].
    ^ retVal
!

reOpen
    "sent after snapin to reopen streams.
     cannot reopen here since I am abstract and have no device knowledge"

    self class name errorPrint. ': cannot reOpen stream - stream closed' errorPrintNL.
    filePointer := nil.
    Lobby unregister:self.
!

setLastError:aNumber
    lastErrorNumber := aNumber
! !

!ExternalStream methodsFor:'queries'!

isBinary
    "return true, if the stream is in binary (as opposed to text-) mode.
     The default when created is false."

    ^ binary
!

isExternalStream
    "return true, if the receiver is some kind of externalStream;
     true is returned here - the method redefined from Object."

    ^ true
!

isReadable 
    "return true, if this stream can be read from"

    ^ (mode ~~ #writeonly)
!

isWritable 
    "return true, if this stream can be written to"

    ^ (mode ~~ #readonly)
! !

!ExternalStream methodsFor:'reading'!

next
    "return the next element; advance read position.
     In binary mode, an integer is returned, otherwise a character.
     If there are no more elements, nil is returned."

%{
    FILE *f;
    int c, nRead;
    OBJ pos, fp;
    unsigned char ch;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
        f = __FILEVal(fp);
        __BEGIN_INTERRUPTABLE__

        if (__INST(buffered) == true) {
            __READING__(f)
        }

        do {
            errno = 0;
            if (__INST(buffered) == false) {
                if ((nRead = read(fileno(f), &ch, 1)) < 1)
                    c = EOF;
                else
                    c = ch;
            } else 
            {
                c = getc(f);
            }
        } while ((c < 0) && (errno == EINTR));
        __END_INTERRUPTABLE__

        if (c != EOF) {
            pos = __INST(position);
            if (__isSmallInteger(pos)) {
                __INST(position) = __MKSMALLINT(__intVal(pos) + 1);
            } else {
                __INST(position) = nil;
            }
            if (__INST(binary) == true) {
                RETURN ( __MKSMALLINT(c & 0xFF) );
            }
            RETURN ( __MKCHARACTER(c & 0xFF) );
        }
/*
        if (errno == EWOULDBLOCK) {
            __INST(hitEOF) = true;
            RETURN(nil);
        }
*/
        __INST(position) = nil;
        
        if (((__INST(buffered) == false) && (nRead < 0))
            || (ferror(f) && (errno != 0))) {
            __INST(lastErrorNumber) = __MKSMALLINT(errno);
        } else {
            __INST(hitEOF) = true;
            RETURN ( nil );
        }
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    self errorWriteOnly
!

next:count
    "return the next count elements of the stream as a collection.
     Redefined to return a String or ByteArray instead of the default: Array."

    |coll|

    binary ifTrue:[
	coll := ByteArray uninitializedNew:count
    ] ifFalse:[
	coll := String new:count
    ].
    self nextBytes:count into:coll startingAt:1.
    ^ coll
!

peek
    "return the element to be read next without advancing read position.
     In binary mode, an integer is returned, otherwise a character.
     If there are no more elements, nil is returned.
     Not allowed in unbuffered mode."

%{
    FILE *f;
    REGISTER int c;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
#ifdef OLD
	if (__INST(buffered) == true) 
#endif
	{
	    f = __FILEVal(fp);

	    __BEGIN_INTERRUPTABLE__
	    __READING__(f)

	    do {
		c = getc(f);
	    } while ((c < 0) && (errno == EINTR));
	    __END_INTERRUPTABLE__

	    if (c != EOF) {
		ungetc(c, f);
		if (__INST(binary) == true) {
		    RETURN ( __MKSMALLINT(c & 0xFF) );
		}
		RETURN ( __MKCHARACTER(c & 0xFF) );
	    }
	    if (ferror(f) && (errno != 0)) {
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    } else {
		__INST(hitEOF) = true;
		RETURN ( nil );
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    buffered ifFalse:[^ self errorNotBuffered].
    ^ self errorWriteOnly
! !

!ExternalStream methodsFor:'reimplemented for speed'!

nextAlphaNumericWord
    "read the next word (i.e. up to non letter-or-digit) after first
     skipping any whiteSpace.
     Return a string containing those characters.
     There is a limit of 1023 characters in the word - if longer,
     it is truncated."

%{  /* STACK: 2000 */
    FILE *f;
    int len;
    char buffer[1024];
    int ch;
    int cnt = 0;
    OBJ fp;

    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	f = __FILEVal(fp);
	__BEGIN_INTERRUPTABLE__
	__READING__(f)

	/*
	 * skip whiteSpace first ...
	 */
	for (;;) {
	    do {
		ch = getc(f);
	    } while ((ch < 0) && (errno == EINTR));

	    if (ch < 0) {
		if (ferror(f) && (errno != 0)) {
		    __INST(lastErrorNumber) = __MKSMALLINT(errno);
		    __END_INTERRUPTABLE__
		    goto err;
		}
		__INST(hitEOF) = true;
		break;
	    }
	    cnt++;

#ifndef NON_ASCII
	    if (ch >= ' ') break;
#endif
	    if ((ch != ' ') && (ch != '\t') && (ch != '\r')
	     && (ch != '\n') && (ch != 0x0b)) break;
	}
	ungetc(ch, f);
	cnt--;

	len = 0;
	for (;;) {
	    do {
		ch = getc(f);
	    } while ((ch < 0) && (errno == EINTR));
	    if (ch < 0) {
		if (ferror(f) && (errno != 0)) {
		    __INST(lastErrorNumber) = __MKSMALLINT(errno);
		    __END_INTERRUPTABLE__
		    goto err;
		}
		__INST(hitEOF) = true;
		break;
	    }

	    ch &= 0xFF;
	    if (! (((ch >= 'a') && (ch <= 'z')) ||
		   ((ch >= 'A') && (ch <= 'Z')) ||
		   ((ch >= '0') && (ch <= '9')))) {
		ungetc(ch, f);
		break;
	    }
	    cnt++;
	    buffer[len++] = ch;
	    if (len >= (sizeof(buffer)-1)) {
		/* emergency */
		break;
	    }
	}
	__END_INTERRUPTABLE__

	if (__INST(position) != nil) {
	    __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + cnt);
	}
	if (len != 0) {
	    buffer[len] = '\0';
	    RETURN ( __MKSTRING_L(buffer, len COMMA_CON) );
	}
	RETURN ( nil );
    }
err: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ self errorWriteOnly
!

nextChunk
    "return the next chunk, i.e. all characters up to the next
     exclamation mark. Within the chunk, exclamation marks have to be doubled -
     except within primitive code (this exception was added to make it easier
     to edit primitive code with external editors). This means, that other
     Smalltalks cannot always read chunks containing primitive code - but that
     doesnt really matter, since C-primitives are an ST/X feature anyway.
     Reimplemented here for more speed."

    |retVal outOfMemory buffer|

    filePointer isNil ifTrue:[^ self errorNotOpen].
    binary ifTrue:[^ self errorBinary].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].

%{  /* STACK: 8000 */
    /*
     * the main trick (and a bit of complication) here
     * is to read the first 4k into a stack-buffer.
     * Since most chunks fit into that, 
     * this avoids creating lots of garbage for thos small chunks.
     */
    FILE *f;
    int done = 0;
    REGISTER int c, lastC;
    int peekC;
    char *bufferPtr = (char *)0;
    char fastBuffer[7000];
    REGISTER int index;
    int currSize, fastFlag;
    int atBeginOfLine = 1, inComment, inString, inPrimitive = 0;

    __INST(lastErrorNumber) = nil;
    f = __FILEVal(__INST(filePointer));

    __READING__(f)

    if (feof(f)) {
	__INST(hitEOF) = true;
	RETURN (nil);
    }

    /*
     * skip spaces
     */
    c = '\n';
    while (! done) {
	lastC = c;

	__BEGIN_INTERRUPTABLE__
	do {
	    c = getc(f);
	} while ((c < 0) && (errno == EINTR));
	__END_INTERRUPTABLE__

	atBeginOfLine = 0;
	switch (c) {
	    case '\n':
	    case ' ':
	    case '\t':
	    case '\r':
	    case '\b':
	    case '\014':
		break;

	    case EOF:
		if (ferror(f) && (errno != 0)) {
		    __INST(lastErrorNumber) = __MKSMALLINT(errno);
		    goto err;
		}
		__INST(hitEOF) = true;
		RETURN (nil);

	    default:
		atBeginOfLine = (lastC == '\n');
		ungetc(c, f);
		done = 1;
		break;
	}
    }

    /*
     * read chunk into a buffer
     */
    bufferPtr = fastBuffer; fastFlag = 1;
    currSize = sizeof(fastBuffer);

    index = 0;
    while (! feof(f)) {
	/* 
	 * do we have to resize the buffer ? 
	 */
	if ((index+2) >= currSize) {
	    OBJ newBuffer;
	    char *nbp;

	    newBuffer = __MKEMPTYSTRING(currSize * 2 COMMA_CON);
	    if (newBuffer == nil) {
		/*
		 * mhmh - chunk seems to be very big ....
		 */
		outOfMemory = true;
		goto err;
	    }
	    nbp = __stringVal(newBuffer);
	    if (!fastFlag) {
		/*
		 * old buffer may have moved - refetch pointer
		 */
		bufferPtr = __stringVal(buffer);
	    }
	    bcopy(bufferPtr, nbp, index);
	    bufferPtr = nbp;
	    bufferPtr[index] = '\0';
	    buffer = newBuffer;
	    fastFlag = 0;
	    currSize = currSize * 2;
	}

	__BEGIN_INTERRUPTABLE__
	do {
	    c = getc(f);
	} while (c < 0 && (errno == EINTR));
	__END_INTERRUPTABLE__

	if (atBeginOfLine && (c == '%')) {
	    __BEGIN_INTERRUPTABLE__
	    do {
		peekC = getc(f);
	    } while (peekC < 0 && (errno == EINTR));
	    __END_INTERRUPTABLE__

	    ungetc(peekC, f);
	    if (peekC == '{') {
		inPrimitive++;
	    } else if (peekC == '}') {
		if (inPrimitive > 0) {
		    inPrimitive--;
		}
	    }
	} else {
	    if (! inPrimitive) {
		if (c == '!') {
		    __BEGIN_INTERRUPTABLE__
		    do {
			c = getc(f);
		    } while (c < 0 && (errno == EINTR));
		    __END_INTERRUPTABLE__

		    if (c != '!') {
			ungetc(c, f);
			break;
		    }
		}
	    }
	}

	if (c < 0) {
	    __INST(hitEOF) = true;
	    if (ferror(f) && (errno != 0)) {
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
		goto err;
	    }
	    break;
	}
	bufferPtr[index++] = c;
	atBeginOfLine =  (c == '\n');
    }

    /*
     * make it a string
     * be careful here - allocating a new string may make the
     * existing buffer move around. Need to check if copying from
     * fast (C) buffer or from real (ST) buffer.
     */
    if (fastFlag) {
	retVal = __MKSTRING_L(bufferPtr, index COMMA_CON);
    } else {
	retVal = __MKSTRING_ST_L(buffer, index COMMA_CON);
    }
err: ;
%}.
    retVal isNil ifTrue:[
	"/
	"/ arrive here with retVal==nil either on error or premature EOF
	"/ or if running out of malloc-memory
	"/
	lastErrorNumber notNil ifTrue:[^ self readError].
	outOfMemory == true ifTrue:[
	    "
	     buffer memory allocation failed.
	     When we arrive here, there was no memory available for the
	     chunk. (seems to be too big of a chunk ...)
	     Bad luck - you should increase the ulimit and/or swap space on your machine.
	    "
	    ^ ObjectMemory allocationFailureSignal raise.
	]
    ].
    ^ retVal
!

nextMatchFor:anObject
    "skip all objects up-to and including anObject, return anObject on success,
     nil if end-of-file is reached before. The next read operation will return
     the element after anObject.
     Only single byte characters are currently supported."

%{
    FILE *f;
    int peekValue, c;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if ((__INST(binary) == true) && __isSmallInteger(anObject)) {
	    peekValue = __intVal(anObject) & 0xFF;
	} else {
	    if ((__INST(binary) != true) && __isCharacter(anObject)) {
		peekValue = __intVal(_characterVal(anObject)) & 0xFF;
	    } else {
		peekValue = -1;
	    }   
	}

	if (peekValue >= 0) {
	    __INST(position) = nil;
	    f = __FILEVal(fp);
	    __BEGIN_INTERRUPTABLE__
	    __READING__(f)

	    for (;;) {
		do {
		    c = getc(f);
		} while ((c < 0) && (errno == EINTR));
                
		if (c == EOF) {
		    __END_INTERRUPTABLE__
		    if (ferror(f) && (errno != 0)) {
			__INST(lastErrorNumber) = __MKSMALLINT(errno);
			break;
		    }
		    __INST(hitEOF) = true;
		    RETURN (nil);
		}
		if (c == peekValue) {
		    __END_INTERRUPTABLE__
		    RETURN (anObject);
		}
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ super nextMatchFor:anObject
!

peekFor:anObject
    "return true and move past next element, if next == something.
     Otherwise, stay and return false. False is also returned
     when EOF is encountered.
     The argument must be an integer if in binary, a character if in
     text mode; only single byte characters are currently supported."

%{
    FILE *f;
    int c;
    int peekValue;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__INST(binary) == true) {
	    if (__isSmallInteger(anObject)) {
		peekValue = __intVal(anObject) & 0xFF;
	    } else {
		goto bad;
	    }
	} else {
	    if (__isCharacter(anObject)) {
		peekValue = __intVal(_characterVal(anObject)) & 0xFF;
	    } else {
		goto bad;
	    }
	}

	f = __FILEVal(fp);

	if (feof(f)) {
	    __INST(hitEOF) = true;
	    RETURN (false);
	}

	__READING__(f)

	errno = 0;
	__BEGIN_INTERRUPTABLE__
	do {
	    if (feof(f)) {
		break;
	    }
	    c = getc(f);
	} while ((c < 0) && (errno == EINTR));
	__END_INTERRUPTABLE__

	if (feof(f)) {
	    __INST(hitEOF) = true;
	}

	if (c == peekValue) {
	    OBJ pos;

	    if ((pos = __INST(position)) != nil) {
		__INST(position) = __MKSMALLINT(__intVal(pos) + 1);
	    }
	    RETURN (true);
	}

	if (c != EOF) {
	    ungetc(c, f);
	    RETURN (false);
	}

	__INST(hitEOF) = true;
	if (ferror(f) && (errno != 0)) {
	    __INST(lastErrorNumber) = __MKSMALLINT(errno);
	} else {
	    RETURN (false);
	}
    }
bad: ;
%}.
    mode == #writeonly ifTrue:[^ self errorWriteOnly].
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ super peekFor:anObject
!

skipLine
    "read the next line (characters up to newline) skip only;
     return nil if EOF reached, self otherwise. 
     Not allowed in binary mode."

%{  /* STACK:2000 */

    FILE *f;
    char buffer[1024];
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__INST(binary) != true) {
	    f = __FILEVal(fp);
            
	    __READING__(f)

	    __BEGIN_INTERRUPTABLE__
	    if (fgets(buffer, sizeof(buffer)-1, f) != NULL) {
		__END_INTERRUPTABLE__
		RETURN ( self );
	    }
	    __END_INTERRUPTABLE__

	    if (ferror(f) && (errno != 0)) {
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    } else {
		__INST(hitEOF) = true;
		RETURN ( nil );
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    binary ifTrue:[^ self errorBinary].
    ^ self errorWriteOnly
!

skipSeparators
    "skip all whitespace; next will return next non-white-space character
     or nil if endOfFile reached. Not allowed in binary mode.
     - reimplemented for speed"

%{
    FILE *f;
    REGISTER int c;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__INST(binary) != true) {
	    f = __FILEVal(fp);
            
	    if (feof(f)) {
		__INST(hitEOF) = true;
		RETURN ( nil );
	    }

	    __READING__(f)

	    __BEGIN_INTERRUPTABLE__
	    while (1) {
		do {
		    if (feof(f)) {
			__END_INTERRUPTABLE__
			__INST(hitEOF) = true;
			RETURN ( nil );
		    }
		    c = getc(f);
		} while ((c < 0) && (errno == EINTR));

		switch (c) {
		    case ' ':
		    case '\t':
		    case '\n':
		    case '\r':
		    case '\b':
		    case '\014':
			break;

		    default:
			__END_INTERRUPTABLE__
			if (c < 0) {
			    __INST(hitEOF) = true;
			    if (ferror(f) && (errno != 0)) {
				__INST(lastErrorNumber) = __MKSMALLINT(errno);
				goto err;
			    }
			    RETURN ( nil );
			}
			ungetc(c, f);
			RETURN ( __MKCHARACTER(c & 0xFF) );
		}
	    }
	}
    }
err: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    ^ self errorBinary.
!

skipSeparatorsExceptCR
    "skip all whitespace but no newlines;
     next will return next non-white-space character
     or nil if endOfFile reached. Not allowed in binary mode.
     - reimplemented for speed"

%{
    FILE *f;
    int c;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__INST(binary) != true) {
	    f = __FILEVal(fp);
	    __READING__(f)

	    __BEGIN_INTERRUPTABLE__
	    while (1) {
                
		if (feof(f)) {
		    __END_INTERRUPTABLE__
		    __INST(hitEOF) = true;
		    RETURN ( nil );
		}

		do {
		    c = getc(f);
		} while ((c < 0) && (errno == EINTR));

		switch (c) {
		    case ' ':
		    case '\t':
		    case '\b':
			break;

		    default:
			__END_INTERRUPTABLE__
			if (c < 0) {
			    if (ferror(f) && (errno != 0)) {
				__INST(lastErrorNumber) = __MKSMALLINT(errno);
				goto err;
			    }
			    __INST(hitEOF) = true;
			    RETURN ( nil );
			}
			ungetc(c, f);
			RETURN ( __MKCHARACTER(c & 0xFF) );
		}
	    }
	}
    }
err: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    ^ self errorBinary
!

skipThrough:aCharacter
    "skip all characters up-to and including aCharacter. Return the receiver if
     skip was successful, otherwise (i.e. if not found) return nil.
     The next read operation will return the character after aCharacter.
     The argument, aCharacter must be character, or integer when in binary mode.
     Only single byte characters are currently supported."

%{
    FILE *f;
    REGISTER int c, cSearch;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(writeonly))) {
	if (__INST(binary) == true) {
	    /* searched for object must be a smallInteger */
	    if (! __isSmallInteger(aCharacter)) goto badArgument;
	    cSearch = __intVal(aCharacter);
	} else {
	    /* searched for object must be a character */
	    if (! __isCharacter(aCharacter)) goto badArgument;
	    cSearch = __intVal(_characterVal(aCharacter));
	}
	/* Q: should we just say: "not found" ? */
	if ((cSearch < 0) || (cSearch > 255)) goto badArgument;

	f = __FILEVal(fp);
	__READING__(f)

	__BEGIN_INTERRUPTABLE__
	while (1) {
#ifdef NOTNEEDED
	    if (feof(f)) {
		__END_INTERRUPTABLE__
		RETURN ( nil );
	    }
#endif
	    do {
		c = getc(f);
	    } while ((c < 0) && (errno == EINTR));

	    if (c == cSearch) {
		__END_INTERRUPTABLE__
		RETURN (self);
	    }
	    if (c < 0) {
		__END_INTERRUPTABLE__
		if (ferror(f) && (errno != 0)) {
		    __INST(lastErrorNumber) = __MKSMALLINT(errno);
		    break;
		} else {
		    __INST(hitEOF) = true;
		    RETURN (nil);
		}
	    }
	}
    }
badArgument: ;
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #writeonly) ifTrue:[^ self errorWriteOnly].
    "
     argument must be integer/character in binary mode, 
     character in text mode
    "
    ^ self error:'invalid argument'.

    "
     |s|
     s := 'Makefile' asFilename readStream.
     s skipThrough:$=.
     s next:10
    "
!

skipThroughAll:aString
    "search & skip for the sequence given by the argument, aCollection;
     return nil if not found, self otherwise. If successful, the next read 
     will return the character after the searchstring."

    |buffer len first|

    (aString isString and:[binary not]) ifTrue:[
	len := aString size.
	first := aString at:1.
	buffer := String new:len.
	buffer at:1 put:first.
	len := len - 1.
	[true] whileTrue:[
	    (self skipThrough:first) isNil ifTrue:[
		^ nil.
	    ].
	    (self nextBytes:len into:buffer startingAt:2) == len ifFalse:[
		^ nil
	    ].
	    buffer = aString ifTrue:[
		"
		 position back, before string
		"
		^ self
	    ].
	].
	"NOT REACHED"
    ].
    ^ super skipThroughAll:aString

    "
     |s|
     s := 'Makefile' asFilename readStream.
     s skipThroughAll:'are'.
     s next:10
    "
!

skipToAll:aString
    "skip for the sequence given by the argument, aCollection;
     return nil if not found, self otherwise. On a successful match, next read
     will return characters of aString."

    |oldPos|

    oldPos := self position.
    (self skipThroughAll:aString) isNil ifTrue:[
	"
	 restore position
	"
	self position:oldPos.
	^ nil
    ].
    "
     position before match-string
    "
    self position:(self position - aString size).
    ^ self

    "
     |s|
     s := 'Makefile' asFilename readStream.
     s skipToAll:'are'.
     s next:10
    "
! !

!ExternalStream methodsFor:'testing'!

atEnd
    "return true, if position is at end"

%{
    FILE *f;
    OBJ fp;
    int c;

    if (__INST(hitEOF) == true) {
	RETURN (true);
    }
    if (__INST(buffered) == false) {
	RETURN (false);
    }

    __INST(lastErrorNumber) = nil;

    if ((fp = __INST(filePointer)) != nil) {
	f = __FILEVal(fp);
#ifdef OLD
	RETURN ( feof(f) ? true : false );
#else
	__READING__(f)

	__BEGIN_INTERRUPTABLE__
	do {
	    c = getc(f);
	} while ((c < 0) && (errno == EINTR) && (clearerr(f), 1));
	__END_INTERRUPTABLE__

	if (c != EOF) {
	    ungetc(c, f);
	    RETURN (false);
	}
	if (ferror(f) && (errno != 0)) {
	    __INST(lastErrorNumber) = __MKSMALLINT(errno);
	} else {
	    __INST(hitEOF) = true;
	    RETURN (true);
	}
#endif
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self readError].
    ^ self errorNotOpen
!

canReadWithoutBlocking
    "return true, if any data is available for reading (i.e.
     a read operation will not block the smalltalk process), false otherwise."

    |fd|

    filePointer isNil ifTrue:[^ self errorNotOpen].
    mode == #writeonly ifTrue:[^ self errorWriteOnly].

    fd := self fileDescriptor.
    ^ OperatingSystem readCheck:fd

    "
     |pipe|

     pipe := PipeStream readingFrom:'(sleep 10; echo hello)'.
     pipe canReadWithoutBlocking ifTrue:[
	 Transcript showCr:'data available'
     ] ifFalse:[
	 Transcript showCr:'no data available'
     ].
     pipe close
    "
!

canWriteWithoutBlocking
    "return true, if data can be written into the stream 
     (i.e. a write operation will not block the smalltalk process)."

    |fd|

    filePointer isNil ifTrue:[^ self errorNotOpen].
    mode == #readonly ifTrue:[^ self errorReadOnly].

    fd := self fileDescriptor.
    ^ OperatingSystem writeCheck:fd
! !

!ExternalStream methodsFor:'waiting for I/O'!

readWait
    "suspend the current process, until the receiver
     becomes ready for reading. If data is already available,
     return immediate. 
     The other threads are not affected by the wait."

    self readWaitWithTimeoutMs:nil
!

readWaitWithTimeout:timeout
    "suspend the current process, until the receiver
     becomes ready for reading or a timeout (in seconds) expired. 
     If data is already available, return immediate. 
     Return true if a timeout occured (i.e. false, if data is available).
     The other threads are not affected by the wait."

    ^ self readWaitWithTimeoutMs:timeout * 1000
!

readWaitWithTimeoutMs:timeout 
    "suspend the current process, until the receiver
     becomes ready for reading or a timeout (in milliseconds) expired. 
     If data is already available, return immediate. 
     Return true if a timeout occured (i.e. false, if data is available).
     The other threads are not affected by the wait."

    |fd inputSema hasData wasBlocked|

    filePointer isNil ifTrue:[^ self errorNotOpen].
    mode == #writeonly ifTrue:[^ self errorWriteOnly].

    fd := self fileDescriptor.
    (OperatingSystem readCheck:fd) ifTrue:[^ false].

    wasBlocked := OperatingSystem blockInterrupts.
    hasData := OperatingSystem readCheck:fd.
    hasData ifFalse:[
	inputSema := Semaphore new.
	[
	    timeout notNil ifTrue:[
		Processor signal:inputSema afterMilliseconds:timeout 
	    ].
	    Processor signal:inputSema onInput:fd.
	    Processor activeProcess state:#ioWait.
	    inputSema wait.
	    Processor disableSemaphore:inputSema.
	    hasData := OperatingSystem readCheck:fd
	] valueOnUnwindDo:[
	    Processor disableSemaphore:inputSema.
	    wasBlocked ifFalse:[OperatingSystem unblockInterrupts].
	]
    ].
    wasBlocked ifFalse:[OperatingSystem unblockInterrupts].
    ^ hasData not
!

writeWait
    "suspend the current process, until the receiver
     becomes ready for writing.
     Return immediate if the receiver is already ready. 
     The other threads are not affected by the wait."

    self writeWaitWithTimeoutMs:nil
!

writeWaitWithTimeout:timeout
    "suspend the current process, until the receiver
     becomes ready for writing or a timeout (in seconds) expired. 
     Return true if a timeout occured (i.e. false, if data is available).
     Return immediate if the receiver is already ready. 
     The other threads are not affected by the wait."

    ^ self writeWaitWithTimeoutMs:timeout * 1000
!

writeWaitWithTimeoutMs:timeout
    "suspend the current process, until the receiver
     becomes ready for writing or a timeout (in seconds) expired. 
     Return true if a timeout occured (i.e. false, if data is available).
     Return immediate if the receiver is already ready. 
     The other threads are not affected by the wait."

    |fd outputSema canWrite wasBlocked|

    filePointer isNil ifTrue:[
	^ self errorNotOpen
    ].
    mode == #readonly ifTrue:[
	^ self errorReadOnly
    ].

    fd := self fileDescriptor.
    (OperatingSystem writeCheck:fd) ifTrue:[^ false].

    wasBlocked := OperatingSystem blockInterrupts.
    canWrite := OperatingSystem writeCheck:fd.
    canWrite ifFalse:[
	outputSema := Semaphore new.
	[
	    timeout notNil ifTrue:[
		Processor signal:outputSema afterMilliseconds:timeout
	    ].
	    Processor signal:outputSema onOutput:fd.
	    Processor activeProcess state:#ioWait.
	    outputSema wait.
	    Processor disableSemaphore:outputSema.
	    canWrite := OperatingSystem writeCheck:fd
	] valueOnUnwindDo:[
	    Processor disableSemaphore:outputSema.
	    wasBlocked ifFalse:[OperatingSystem unblockInterrupts].
	]
    ].
    wasBlocked ifFalse:[OperatingSystem unblockInterrupts].
    ^ canWrite not
! !

!ExternalStream methodsFor:'writing'!

commit
    "write all buffered date - ignored if unbuffered"

    self synchronizeOutput
!

cr
    "append an end-of-line character (or CRLF if in crlf mode).
     reimplemented for speed"

%{
    FILE *f;
    int len, cnt;
    OBJ fp;
    char *cp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))) {
	if (__INST(binary) != true) {
	    f = __FILEVal(fp);

	    if (__INST(useCRLF) == true) {
		cp = "\r\n"; len = 2;
	    } else {
		cp = "\n"; len = 1;
	    }
	    __BEGIN_INTERRUPTABLE__

	    if (__INST(buffered) == true) {
		__WRITING__(f)
		cnt = fwrite(cp, 1, len, f);
	    } else {
		do {
		    cnt = write(fileno(f), cp, len);
		} while ((cnt < 0) && (errno == EINTR));
	    }

	    __END_INTERRUPTABLE__

	    if (cnt == len) {
		if (__INST(position) != nil) {
		    __INST(position) = __MKSMALLINT(__intVal(__INST(position)) + len);
		}
		RETURN ( self );
	    }
	    __INST(lastErrorNumber) = __MKSMALLINT(errno);
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    self errorBinary
!

nextPut:aCharacter
    "write the argument, aCharacter - return nil if failed, self if ok.
     Only single-byte characters are currently supported"

%{
    FILE *f;
    char c;
    int cnt;
    OBJ pos, fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil) 
     && (__INST(mode) != @symbol(readonly))) {
	if (__INST(binary) != true) {
	    if (__isCharacter(aCharacter)) {
		c = __intVal(__characterVal(aCharacter)) & 0xFF;
    doWrite:
		f = __FILEVal(fp);

		__BEGIN_INTERRUPTABLE__

		if (__INST(buffered) == true) {
		    __WRITING__(f)

		    do {
			cnt = fwrite(&c, 1, 1, f);
		    } while ((cnt != 1) && (errno == EINTR));
		} else {
		    do {
			cnt = write(fileno(f), &c, 1);
		    } while ((cnt != 1) && (errno == EINTR));
		}

		__END_INTERRUPTABLE__

		if (cnt == 1) {
		    pos = __INST(position);
		    if (pos != nil) {
			__INST(position) = __MKSMALLINT(__intVal(pos) + 1);
		    }
		    RETURN ( self );
		}
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    }
	} else {
	    if (__isSmallInteger(aCharacter)) {
		c = __intVal(aCharacter);
		goto doWrite;
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].
    binary ifFalse:[^ self argumentMustBeCharacter].
    ^ self argumentMustBeInteger.
!

nextPutAll:aCollection
    "write all elements of the argument, aCollection.
     Reimplemented for speed when writing strings or byteArrays.
     For others, falls back to general method in superclass."

%{
    FILE *f;
    unsigned char *cp;
    int len, cnt;
    OBJ pos, fp;
    int offs;

    __INST(lastErrorNumber) = nil;

    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))) {
        cp = NULL;
        offs = 0;
        if (__isString(aCollection) || __isSymbol(aCollection)) {
            cp = __stringVal(aCollection);
            len = __stringSize(aCollection);
        } else {
            if (__INST(binary) == true) {
                if (__isByteArray(aCollection)) {
                    cp = __ByteArrayInstPtr(aCollection)->ba_element;
                    len = _byteArraySize(aCollection);
                } else {
                    if (__isBytes(aCollection)) {
                        int nInst;

                        cp = __ByteArrayInstPtr(aCollection)->ba_element;
                        len = _byteArraySize(aCollection);
                        nInst = __intVal(__ClassInstPtr(__qClass(aCollection))->c_ninstvars);
                        offs = __OBJS2BYTES__(nInst);
                        cp += offs;
                        len -= offs;
                    }
                }
            }
        }
        if (cp != NULL) {
            f = __FILEVal(fp);


            if (__INST(buffered) == false) {
                int cc, rest;

                cnt = 0;
                rest = len;
                /*
                 * partial writes seem to be possible
                 * with ttys when interrupted ...
                 * I do not like this
                 */
                do {
                    cp = __ByteArrayInstPtr(aCollection)->ba_element + offs;
                    cc = write(fileno(f), cp, rest);
                    if (cc > 0) {
                        cnt += cc;
                        offs += cc;
                        rest -= cc;
                    } else if (cc < 0) { 
                        if (errno != EINTR) {
                            break;
                        }
                    }
                    __HANDLE_INTERRUPTS__
                } while (rest);
            } else {
                __BEGIN_INTERRUPTABLE__
                __WRITING__(f)
                cnt = fwrite(cp, 1, len, f);
                __END_INTERRUPTABLE__
                if (errno == EINTR) errno = 0;
            }


            if (cnt == len) {
                pos = __INST(position);
                if (pos != nil) {
                    __INST(position) = __MKSMALLINT(__intVal(pos) + len);
                }
                RETURN ( self );
            }
            __INST(lastErrorNumber) = __MKSMALLINT(errno);
        }
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    filePointer isNil ifTrue:[^ self errorNotOpen].
    (mode == #readonly) ifTrue:[^ self errorReadOnly].

    ^ super nextPutAll:aCollection
!

nextPutAll:aCollection startingAt:start to:stop
    "write a range of elements of the argument, aCollection.
     Reimplemented for speed when writing strings or byteArrays.
     For others, falls back to general method in superclass."

%{
    FILE *f;
    unsigned char *cp;
    int offs, len, cnt, index1, index2;
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if (((fp = __INST(filePointer)) != nil)
     && (__INST(mode) != @symbol(readonly))) {
	if (__bothSmallInteger(start, stop)) {
	    cp = NULL;
	    offs = 0;
	    if (__INST(binary) != true) {
		if (__isString(aCollection) || __isSymbol(aCollection)) {
		    cp = __stringVal(aCollection);
		    len = __stringSize(aCollection);
		}
	    } else {
		if (__isByteArray(aCollection)) {
		    cp = __ByteArrayInstPtr(aCollection)->ba_element;
		    len = _byteArraySize(aCollection);
		} else {
		    if (__isBytes(aCollection)) {
			int nInst;

			cp = __ByteArrayInstPtr(aCollection)->ba_element;
			len = _byteArraySize(aCollection);
			nInst = __intVal(__ClassInstPtr(__qClass(aCollection))->c_ninstvars);
			offs = __OBJS2BYTES__(nInst);
			cp += offs;
			len -= offs;
		    }
		}
	    }

	    if (cp != NULL) {
		f = __FILEVal(fp);

		index1 = __intVal(start);
		index2 = __intVal(stop);
		if ((index1 < 1) || (index2 > len) || (index2 < index1)) {
		    RETURN ( self );
		}
		if (index2 > len)
		    index2 = len;

		len = index2 - index1 + 1;

		__BEGIN_INTERRUPTABLE__

		if (__INST(buffered) == true) {
		    __WRITING__(f)
		    cnt = fwrite(cp+index1-1, 1, len, f);
		} else {
		    do {
			cp = __ByteArrayInstPtr(aCollection)->ba_element + offs;
			cnt = write(fileno(f), cp+offs, len);
		    } while ((cnt < 0) && (errno == EINTR));
		}

		__END_INTERRUPTABLE__

		if (cnt == len) {
		    if (__INST(position) != nil) {
			__INST(position) = __MKSMALLINT(__intVal(__INST(position)) + len);
		    }
		    RETURN ( self );
		}
		__INST(lastErrorNumber) = __MKSMALLINT(errno);
	    }
	}
    }
%}.
    lastErrorNumber notNil ifTrue:[^ self writeError].
    ^ super nextPutAll:aCollection startingAt:start to:stop
!

synchronizeOutput
    "write all buffered data - ignored if unbuffered"

%{
    OBJ fp;

    __INST(lastErrorNumber) = nil;
    if ((fp = __INST(filePointer)) != nil) {
	if (__INST(mode) != @symbol(readonly)) {
	    if (__INST(buffered) == true) {
		__BEGIN_INTERRUPTABLE__
		fflush( __FILEVal(fp) );
		__END_INTERRUPTABLE__
	    }
	}
    }
%}
! !

!ExternalStream class methodsFor:'documentation'!

version
    ^ '$Header: /cvs/stx/stx/libbasic/ExternalStream.st,v 1.97 1996-04-07 02:12:19 cg Exp $'
! !
ExternalStream initialize!