#include <protocol/protocol.h>

typedef struct chain {
  layer next;
  int strict;
} *chain;

static void from_below (layer l,pbuffer b, int f)
{ 
 chain c=(chain)l->state;
 pbuffer d;
 int len;
 
 if (c->strict && b){
   len=buffer_length(b);
   d=allocate_downwards_buffer(c->next,len);
   buffer_copy(d,0,b,0,len);
   write_down(c->next,d,f);
   dereference_buffer(d);
 } else {
   write_down(c->next,b,f);
 }
 if (l->up) write_up(l,b,f); /* hack*/
}

static void write_chain(layer l,pbuffer b,int f)
{
  chain c=(chain)l->state;
  write_up(c->next,b,f);
}


layer add_chain(layer l,int strict)
{
  chain old=(chain)l->state;
  chain m=(chain)allocate_memory(sizeof(struct chain));
  layer new=create_layer(m,write_chain,from_below,0);
  m->strict=1;
  m->next=old->next;
  old->next=new;
  return(new);
}

layer create_chain(int strict)
{
  layer l;
  chain m=(chain)allocate_memory(sizeof(struct chain));
  m->strict=1;
  return(m->next=create_layer(m,write_chain,from_below,0));
}


