/**********************************************************************
 
	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	"memory_debug.h"
#include	"task.h"
#include	"stream.h"

SEM stream_lock;
extern STREAM ** recv_streams;
extern int recv_streams_len;
extern S_TABLE * stream_table_list;


S_TABLE *
_search_type(char type)
{
S_TABLE * ret;
	ret = stream_table_list;
	for ( ; ret ; ret = ret->next )
		if ( ret->type == type )
			return ret;
	return 0;
}

void
write_msg(char * str)
{
char * msg;
char * p, * q;
int i;
	msg = d_alloc(strlen(str));
	p = &str[1];
	q = msg;
	for ( ; *p ; ) {
		if ( *p == ']' )
			break;
		if ( *p == '\\' ) {
			*q++ = ((p[1]-'0')<<6)|
				((p[2]-'0')<<3)|
				(p[3]-'0');
			p += 4;
		}
		else *q++ = *p++;
	}
	*q = 0;
	for ( i = 0 ; i < recv_streams_len ; i ++ ) {
		s_write(recv_streams[i],msg,strlen(msg));
		s_flush(recv_streams[i]);
	}
	d_f_ree(msg);
}


void
proc_recv_stream(char * msg)
{
PROC_RECV pr;
int i;
	lock_task(stream_lock);

	recv_streams = d_alloc(sizeof(STREAM*));
	i = 0;

	pr.ptr = msg+1;
	pr.fidp = 3;
	for ( ; *pr.ptr ; ) {
		if ( *pr.ptr == '[' )
			break;
		pr.tbl = _search_type(*pr.ptr);
		if ( pr.tbl == 0 ) {
			recv_streams[i++] = 0;
			pr.ptr ++;
		}
		else	recv_streams[i++] = (*pr.tbl->proc_recv)(&pr);
		recv_streams = d_re_alloc(
			recv_streams,
			sizeof(STREAM*)*(i+1));
	}
	recv_streams[i] = 0;
	recv_streams_len = i;
	unlock_task(stream_lock,"proc_recv_stream");
	if ( *pr.ptr == '[' )
		write_msg(pr.ptr);
}

