#include <stdio.h>

int l1_read( char *b);
int l1_write(char b);

// layer 2 deals with blocks, so there has to be a block length
// we send the block length as 3 ASCII digits - max length is 999
// if the maxlen parameter is too small we return an error.


int l2_read( char *b, int max) {
  int i;
  int len;
  char x;
  char buf[5];
  

  // read the length
  for (i=0;i<4;i++) {
    if (l1_read(buf+i)!=1) 
      return(-1);
  }

  buf[4]=0;
  len = atoi(buf);
  if (len>max) {
    return(-1);
  }

  
  for (i=0;i<len;i++) {
    if (l1_read(b+i)!=1) 
    return(-1);
  }

  return(len);
}


int l2_write(char *b, int n) {
  int i;
  char buf[5];
  // send length
  sprintf(buf,"%04d",n);

  for (i=0;i<4;i++) {
    if (l1_write(buf[i])!=1) 
      return(-1);
  }

  for (i=0;i<n;i++) {
    if (l1_write(b[i])!=1) 
      return(-1);
  }

  return(n);
}


