
/*
   common functions for hacking streamoids
*/

#include "io-defs.h"
#include <file.h>
#include <errno.h>
#include <osbind.h>

int _stream_default_buffer_size;

#define stream_buffer_size (_stream_default_buffer_size ? : 8192)

/*
   vector of pointers to open streamoids.
*/
static struct streamoid ** all_open_streamoids = (struct streamoid ** )0;
static int n_streamoid_slots = 0;

local void add_open_streamoid(s)
struct streamoid * s;
{
  int i;

  for (i = 0 ; i < n_streamoid_slots ; i++)
	if (all_open_streamoids[i] == (struct streamoid * )0)
		{
		all_open_streamoids[i] = s;
		return;
		}
/* need to add more slots */
  n_streamoid_slots += 4;
  if (all_open_streamoids)
	all_open_streamoids = 
	  (struct streamoid ** )realloc(all_open_streamoids, 
				       n_streamoid_slots * 
				        sizeof(struct streamoid **));
    else
	all_open_streamoids =
	  (struct streamoid ** )malloc(n_streamoid_slots * 
				      sizeof(struct streamoid **));
  for (i = n_streamoid_slots - 4 ; i < n_streamoid_slots ; i++)
	all_open_streamoids[i] = (struct streamoid * )0;
  all_open_streamoids[n_streamoid_slots - 4] = s;
}

void __remove_open_streamoid(s)
struct streamoid * s;
{
  int i;

  for (i = 0 ; i < n_streamoid_slots ; i++)
	if (all_open_streamoids[i] == s)
		all_open_streamoids[i] = (struct streamoid * )0;
}

/*
   canonical function for opening a streamoid.
*/
struct streamoid * __make_stream(handle, flags, select_methods, eof_p)
int handle;				/* the handle to use */
int flags;				/* flags to init it with */
void (* select_methods)();		/* fun to call to construct methods */
int eof_p;				/* open at eof */
{
  struct streamoid * s;

  s = (struct streamoid * )malloc(sizeof(struct streamoid));
  bzero(s, sizeof(struct streamoid));
  if (flags & STR_BUFFERED_P)
	{
	s->buffer = (unsigned char * )
		malloc(s->buffer_size = stream_buffer_size);
	}
  s->gemdos_handle = handle;
  if (eof_p)
	{
	s->file_position = Fseek(0, handle, L_XTND);
	flags |= STR_AT_EOF_P;
	}
    else
	s->file_position = 0;
  (*select_methods)(s, flags);
  s->flags = flags | STR_OPEN_P;
  add_open_streamoid(s);
  return(s);
}

void __close_all_streamoids()
{
  int i;
  
  for (i = 0 ; i < n_streamoid_slots ; i++)
	if (all_open_streamoids[i])
		method_call_0(all_open_streamoids[i], METHOD_CLOSE);
}
