/**********************************************************************
 
	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.

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


#include	"memory_debug.h"
#include	"stream.h"


int
s_copy_to_stream(int * ret_len,STREAM * s1,STREAM * s2,int len)
{
char * buf;
int er,er2;
int ret;
int _ret;
int _ret_len;
	if ( len == -1 ) {
		buf = d_alloc(4096,123);
		ret = 0;
		_ret = 0;
		for ( ; ; ) {
			er = s_read(s1,buf,4096);
			if ( er < 0 ) {
				_ret = S_COPY_TO_STREAM_SRC_ERR;
				break;
			}
			if ( er == 0 ) {
				_ret = 0;
				break;
			}
			if ( en_do(&_ret_len,s_write,s2,buf,er) < 0 ) {
				_ret = S_COPY_TO_STREAM_DEST_ERR;
				break;
			}
			ret += er;
		}
		d_f_ree(buf);
	}
	else {
		buf = d_alloc(len,123);
		ret = 0;
		_ret = 0;
		for ( ; len ; ) {
			er = s_read(s1,buf,len);
			if ( er < 0 ) {
				_ret = S_COPY_TO_STREAM_SRC_ERR;
				break;
			}
			if ( er == 0 ) {
				_ret = S_COPY_TO_STREAM_SRC_ERR;
				break;
			}
			if ( en_do(&_ret_len,s_write,s2,buf,er) < 0 ) {
				_ret = S_COPY_TO_STREAM_DEST_ERR;
				break;
			}
			len -= er;
			ret += er;
		}
		d_f_ree(buf);
	}
	*ret_len = ret;
	return _ret;
}
