// loads json array of strings, outs is optional
void keyLoad(const char *array, int *outs, unsigned long at) {
  unsigned short *index;
  unsigned int i;
  unsigned int oi=1;

  if (!array || !*array) {
    return;
  }

  index = (unsigned short*)malloc(strlen(array));
  if (!index) {
    outs[0] = 0;
    return;
  }
  j0g((char*)array, index, strlen(array));

  for (i=0; index[i]; i+=2) {
    int k = keyMap(j0g_safe(i, (char*)array, index), at);
    if (outs) {
      outs[oi++] = k;
    }
  }

  if (outs) {
    outs[0] = oi-1;
  }

  free(index);
}
// this is called on the main loop to try to (re)connect to the HQ
void leadHQHandle(void) {
  static char *buffer = NULL;
  uint8_t block[128];
  char *nl;
  int rsize, len;
  unsigned short index[32]; // <10 keypairs in the incoming json

  // only continue if new data to read
  if (!Scout.wifi.client.available()) {
    return;
  }

  // check to initialize our read buffer
  if (!buffer) {
    buffer = (char*)malloc(1);
    *buffer = 0;
  }

  // get all waiting data and look for packets
  while (rsize = Scout.wifi.client.read(block, sizeof(block))) {
    len = strlen(buffer);

    // process chunk of incoming data
    buffer = (char*)realloc(buffer, len + rsize + 1);
    if (!buffer) {
      return; // TODO, realloc error, need to restart?
    }
    memcpy(buffer + len, block, rsize);
    buffer[len + rsize] = 0; // null terminate

    // look for a packet
    if (hqVerboseOutput) {
      sp("looking for packet in: ");
      speol(buffer);
    }
    nl = strchr(buffer, '\n');
    if (!nl) {
      continue;
    }

    // null terminate just the packet and process it
    *nl = 0;
    j0g(buffer, index, 32);
    if (*index) {
      leadIncoming(buffer, index);
    } else {
      if (hqVerboseOutput) {
        speol("JSON parse failed");
      }
    }

    // advance buffer and resize, minimum is just the buffer end null
    nl++;
    len = strlen(nl);
    memmove(buffer, nl, len+1);
    buffer = (char*)realloc(buffer, len+1); // shrink
  }
}