 {
   static int cnt=0;
   boolean timeouts=false;
+  boolean cntTimeouts,cntChanges;
   boolean changes=false;
   time_t ts=now();
   int chcnt=(sizeof(adArr) / sizeof(struct ad));

      iot.name(ad[chan].name);
      iot.addValue(ad[chan].measured.analog,chbuf);
      iot.next();
      sendingad=true;
    }
  }

  // counter build part
  if (sendingad) // if already sending ad values, add counters a bit earlier to same packet
    timeout=(ts-cntArr[0].last_send > measTimeout-300);
  else
    timeout=(ts-cntArr[0].last_send > measTimeout);
  float diff=abs(cntArr[0].measured.analog-cntArr[0].prevsnd.analog);
  bool changed;
  float limit;
  float val;

  limit = cntArr[0].diff.analog * (1.0 + cntArr[0].measured.analog * cntArr[0].diff_factor.analog);
  changed=(diff > limit);
  if (changed) {
    if (ts-cntArr[0].last_send > 30) {
      if (cntArr[0].avg_samples > 3) {
        // calculate average from previous samples
	val=(cntArr[0].avg_counter / cntArr[0].avg_samples) / (cntArr[0].scale.digital * cntArr[0].scale.analog);
      }
      else
	val=cntArr[0].prev.analog;

      buildTime(ts-10,prevtime);
      iot.name(cntArr[0].name);
      iot.addValue(val,prevtime);
      iot.addValue(cntArr[0].measured.analog,chbuf);
      iot.next();
      cntPrepareForNext(0,ts);
     }
    else {
      iot.name(cntArr[0].name);
      iot.addValue(cntArr[0].measured.analog,chbuf);
      iot.next();
      cntPrepareForNext(0,ts);
    }
  }
  else if (timeout) {
    val=(cntArr[0].avg_counter / cntArr[0].avg_samples) / (cntArr[0].scale.digital * cntArr[0].scale.analog); 
    iot.name(cntArr[0].name);
    iot.addValue(val,chbuf);
    iot.next();
    cntPrepareForNext(0,ts);
  }



  cntArr[index].prevsnd.analog=cntArr[index].measured.analog;
  cntArr[index].avg_samples=0;
  cntArr[index].avg_counter=0;
  cntArr[index].flags &= ~FLAGS_DATACHANGE;
  cntArr[index].flags &= ~FLAGS_TIMEOUT;
}

boolean chkCntTimeouts(time_t ts,boolean advance)
{
  boolean ret=false;
  int timeout;

  timeout= measTimeout;
  if (advance)
    timeout-=300;

  for (int i=0;i<(sizeof(cntArr) / sizeof(struct cnt)); i++) {
    if (ts-cntArr[i].last_send > timeout) {
      cntArr[i].flags |= FLAGS_TIMEOUT;
      ret=true;
    }
  }
  return ret;
}

boolean chkCntChanged()
{
  float limit;
  bool changed;
  float diff;
  boolean ret=false;

  for (int i=0;i<(sizeof(cntArr) / sizeof(struct cnt));i++) {
    diff = abs(cntArr[i].measured.analog-cntArr[i].prevsnd.analog);
    limit = cntArr[i].diff.analog * (1.0 + cntArr[i].measured.analog * cntArr[i].diff_factor.analog);
    if (diff > limit) {
      cntArr[i].flags |= FLAGS_DATACHANGE;
      ret=true;
    }
  }
  return ret;
}

void sendM2X(struct ad *ad,int cnt)
