/*
Usage:
	
Plink* plink_create(void);  - Create pipes.    
plink_addref(Plink *p);
plink_free(Plink);


Ptalk *ptalk_open(int lclchan, Plink *plink); - Open a link




*/

typedef struct {int *pin; int *pout; int nref;} Plink;
typedef struct {Plink *plink; int lclchan;  int rmtchan; int writeok;} Ptalk;
static Ptalk *chantalk[MAX_CHAN];

Ptalk *ptalk_open(int chan, Plink *plink )
{

	chantalk[chan] = p;
	return p;
}
int ptalk_write_ok(Ptalk *p)
{
	return p->writeok;
}
int ptalk_write(Ptalk *p, char *bf, int len)
{
	return plink_write(p->plink,p->rmtchan,P_DATA,bf,len);
}
int ptalk_read_pause(Ptalk *p, int t)
{
	return plink_write(p->plink,p->rmtchan,t ? P_STOP : P_START,"",0);	
}
int ptalk_accept(Plink *p, int lclchan, int rmtchan)
{
	return plink_write(p,lclchan,rmtchan,P_OPENED,NULL,0);
}
int ptalk_read(Plink *p,  int *lclchan,  char *bf, int maxlen, int *retlen)
{
	int t;
	int lclchan;
	Ptalk *pt;
	if (!plink_read(p->plink,*t,&lclchan,bf,maxlen,retlen)) return FALSE;
	if (t==P_OPEN) return TRUE; 
	if (lclchan<0) return FALSE;
	if (lclchan>=MAXCHAN) return FALSE;
	pt = chantalk[lclchan)
	if (t==P_STOP) {
		
	}
	if (t==P_OPENED) {
	}
}
int ptalk_create(int *in, int *out)
{
	int pread[2],pwrite[2];
	if (pipe_create(pread,3000,_O_BINARY)!=0) { perror("Could not create pipes"); return FALSE; }
	if (pipe_create(pwrite,PIPE_BIG,_O_BINARY)!=0) { perror("Could not create pipes"); return FALSE; }
	sprintf(cread,"%d",pwrite[0]);
	sprintf(cwrite,"%d",pread[1]);
	emsg("Creating process %s %s\n",cread,cwrite);
}

typedef struct {int type; int lclchan; int rmtchan; int len; } Packet;
int plink_read(Plink *plink, int *lclchan, int *type, char *bf, int maxlen, int *retlen)
{
	Packet rec;
	n = pipe_read(plink->pin,&rec,sizeof(rec));
	if (n<sizeof(rec)) return FALSE;
	if (rec->len>maxlen) return FALSE; 
	if (rec->len>0) {
		n = pipe_read(plink->pin,bf,rec->len);
		if (n!=rec->len) return FALSE;
	}
	*lclchan = rec->rmtchan;
	*type = rec->type;

	if (rec->type==P_OPEN) {
		ptalk_accept(plink,
	}
	return TRUE;
}
int plink_write(Plink *l, int lclchan, int rmtchan, int t, char *bf, int len)
{
	int r;
	Packet rec;
	rec->type = t;
	rec->rmtchan = rmtchan;
	rec->lclchan = lclchan;
	rec->len = len;
	r = pipe_write(plink->pout,&rec,sizeof(rec));
	if (r<sizeof(rec)) return FALSE;

	if (len>0) {
		r = pipe_write(l->pout,bf,len);
		if (r!=len) return FALSE;
	}
	return TRUE;
}
Ptalk *ptalk_new(Plink *l, int lclchan) 
{
	/* To create a channel, send a request to open.
	   We will then receive back an
	  which will return
	*/
	Ptalk *t;
	if (!plink_write(lclchan,-1,P_OPEN,NULL,0)) return NULL;
	t = calloc(sizeof(Ptalk),1);
	t->lclchan = lclchan;
	t->plink = l;
	t->rmtchan = -1;
	t->writeok = FALSE;	
	return NULL;
}
