# __DRIVER_CODE__ imports

cdef extern from "zmq.h":
  int zmq_close(void *s)
  int zmq_ctx_destroy(void *context)
  void *zmq_ctx_new()
  void *zmq_socket(void *, int type)
  int zmq_bind(void *s, const char *addr)
  int zmq_recv(void *s, void *buf, size_t len, int flags)


# __DRIVER_CODE__ variables

cdef void *dish
cdef void *context


# __DRIVER_CODE__ setup

context = zmq_ctx_new()
if (not context):
  die("Could not create ZMQ context.\n")
dish = zmq_socket(context, ZMQ_DISH)
if (not dish):
  die("Could not create ZMQ socket.\n")
rc = zmq_bind(dish, "udp://{{in_signal['args']['addr']}}:{{in_signal['args']['port']}}")
assert (rc == 0)

{{sig}}BufVars[6] = {{2 * args['schema']['max_packets_per_tick'] * args['schema']['data']['size']}}
{{sig}}BufVars[5] = {{args['schema']['data']['size']}}


# __DRIVER_CODE__ read

  recvLen = zmq_recv(dish, inBuf, packetSize, 0)
  if (recvLen == -1):
    die("zmq_recv error.\n")


# __DRIVER_CODE__ parser update

  {{sig}}BufVars[2] += {{args['schema']['data']['size']}} # same as {{sig}}BufVars[5]
  {{sig}}BufVars[10] += 1
  if ({{sig}}BufVars[7] <= {{sig}}BufVars[2] + {{sig}}BufVars[6]):
    {{sig}}BufVars[4] = {{sig}}BufVars[2]
    {{sig}}BufVars[12] = {{sig}}BufVars[10]
  elif ({{sig}}BufVars[2] > {{sig}}BufVars[4]):
    {{sig}}BufVars[4] = {{sig}}BufVars[2] 
    {{sig}}BufVars[12] = {{sig}}BufVars[10]
  # Somehow when there is no active streaming data, this number just runs upwards
  {{sig}}BufVars[3] += {{sig}}BufVars[5]
  {{sig}}BufVars[11] += 1
  {%- endif %}
  {%- if not has_parser %}
  if pNumTicks[0] < 0 and ({{sig}}BufVars[7] < {{sig}}BufVars[2] + {{sig}}BufVars[6]):
    {{sig}}BufVars[2] = 0
    {{sig}}BufVars[10] = 0
  # inBuf = <{{in_dtype}}*>(<uint8_t*>inBuf + recvLen)
  # if (inBuf >= inBufEnd):
  #   inBuf = inBufStrt


# __DRIVER_CODE__ exit_handler

  zmq_close(dish)
  zmq_ctx_destroy(context)
