#include "join.h"
#include "fmt.h"

void join(char *dest, unsigned len, const char *sep, const char * const * list,
    unsigned n) {
  int i;
  int flag_first;

#define addstring(x) do { \
  unsigned r; \
  r = fmt_strn(dest,(x),len); \
  dest += r; \
  len -= r; \
} while(0)

  /* for trailing NUL */
  len -= 1;

  flag_first = 1;
  for(i = 0; i < n; i++) {
    if(flag_first) flag_first = 0;
    else addstring(sep);

    addstring(list[i]);
  }
  
  *dest = 0;
}
