#include "ka_vars.h"

#include <string.h>
#include "ka_mem.h"

typedef struct var_s var_t;

struct var_s
{
  var_t* next;
  const char* name;
  const void* value;
};

struct ka_vars_s
{
  int nr_vars;
  var_t* varlist;
};

ka_vars_t* ka_new_vars(void)
{
  return ka_mem_calloc(sizeof(ka_vars_t));
}

void ka_delete_vars(ka_vars_t** pvars)
{
  ka_vars_t* vars = *pvars;
  *pvars = NULL;

  if (vars)
  {
    var_t* v = vars->varlist;
    while (v)
    {
      var_t* n = v->next;
      ka_mem_free(v);
      v = n;
    }
    ka_mem_free(vars);
  }
}

const void* ka_vars_get(ka_vars_t* vars, const char* varname)
{
  var_t* pvars = vars->varlist;

  while (pvars)
  {
    if (!strcmp(pvars->name, varname))
      return pvars->value;
  }

  return NULL;
}

void ka_vars_set(ka_vars_t* vars, const char* varname, const void* value)
{
  var_t* pvar = vars->varlist;

  while (pvar)
  {
    if (!strcmp(pvar->name, varname))
    {
      pvar->value = value;
      return;
    }
  }

  pvar = ka_mem_alloc(sizeof(*pvar));
  if (pvar)
  {
    pvar->name = varname;
    pvar->value = value;
    pvar->next = vars->varlist;
    vars->varlist = pvar;
  }
}
