#! /bin/env tclsh

package require critcl
::critcl::tcl 8.6

::critcl::cheaders clib.h
::critcl::ccode {
	#include "clib.h"
	void filter (Tcl_Interp *interp ,Tcl_Channel inchan ,Tcl_Channel outchan, ycl_chan_process process) {
		int i ,utflen ,len ,outidx ,readsize = 65536 ,written;
		char *utfstring;
		Tcl_UniChar *uchar , *ustring;
		Tcl_Obj *chars = Tcl_NewObj() , *ucharobj = Tcl_NewIntObj(0);
		Tcl_IncrRefCount(chars);
		Tcl_DString data;
		Tcl_DStringInit(&data);
		while (1) {
			len = Tcl_ReadChars(inchan ,chars ,readsize ,0);
			ustring = Tcl_GetUnicode(chars);
			for (i = 0; i < len; i++) {
				uchar = ustring + i;
				process(interp ,uchar ,&data);
			}
			utfstring = Tcl_DStringValue(&data);
			utflen = Tcl_DStringLength(&data);
			written = 0;
			while (written < utflen) {
				written += Tcl_WriteChars(outchan , utfstring + written ,(utflen - written));
			}
			Tcl_DStringSetLength(&data ,0);
			if (Tcl_Eof(inchan)) {
				break;
			}
		}
		Tcl_DecrRefCount(chars);
	}
}
::critcl::api header clib.h
::critcl::api function void filter {
	Tcl_Interp *interp Tcl_Channel inchan Tcl_Channel
	outchan ycl_chan_process process
}
::critcl::load

if 0 {
	package provide ycl_chan_clib 0.1
}
