/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/


#define STREAM_LIB

#include	<errno.h>
#include	"stream.h"
#include	"task.h"
#include	"utils.h"
#include	"pri_level.h"

extern SEM stream_lock;

int
s_read(STREAM * s,void * data,int len)
{
S_TABLE * tbl;
S_FILE_THREAD t;
int ret;
int pri;
	pri = push_pri(PRI_NETWORK);

	lock_task(stream_lock);
	if ( len <= 0 ) {
		unlock_task(stream_lock,"s_read");
		change_pri(0,pri);
		return -1;
	}
	if ( s == 0 ) {
		unlock_task(stream_lock,"s_read");
		change_pri(0,pri);
		return -1;
	}
	if ( s->h.tbl == 0 ) {
		unlock_task(stream_lock,"s_read");
		change_pri(0,pri);
		return -1;
	}
	if ( s->h.pushed_flag ) {
		*(char*)data = s->h.pushed;
		s->h.pushed_flag = 0;
		unlock_task(stream_lock,"s_read");
		change_pri(0,pri);
		return 1;
	}
	tbl = s->h.tbl;
	_s_insert_thread(s,&t);

	unlock_task(stream_lock,"s_read");

	ret = (*tbl->read)(s,data,len);

	lock_task(stream_lock);
	s->h.bytes_per_interval += ret;
	unlock_task(stream_lock,"s_read");

	s_delete_thread(s,&t);

	change_pri(0,pri);

	return ret;
}

