#include "im.h"

static ImContext *context_stack;

/**
 * im_context_new - allocate a new ImContext structure.
 *
 * Allocate and return a new ImContext structure.
 *
 */
ImContext *im_context_new(void) {
  ImContext *ctx = p_malloc(sizeof(ImContext));
  memset(ctx, 0, sizeof(ImContext));
  return ctx;
}

/**
 * im_context_free - Free an existing ImContext structure.
 * @ctx: ImContext *, Specified render context.
 *
 * Free an existing ImContext structure.  The context structure is
 * removed from the context stack if it is in there.  Note that this may
 * change the current render context!
 *
 */
void im_context_free(ImContext *ctx) {
  ImContext *i, *prev = NULL;

  if (context_stack) {
    for (prev = NULL, i = context_stack; i; prev = i, i = i->next) {
      if (i == context) {
        if (prev)
          prev->next = i->next;
        else
          context_stack = i->next;

        break;
      }
    }
  }

  p_free(ctx);
}

/**
 * im_context_push - Push the specified context onto the context stack.
 * @ctx: ImContext *, Specified render context.
 *
 * Push the specified context onto the context stack, making it the
 * active context.
 *
 */
void im_context_push(ImContext *ctx) {
  ctx->next = context_stack;
  context_stack = ctx;
}

/**
 * im_context_pop - Pop and return the top context from the context stack.
 *
 * Pop and return the top context from the context stack.  Returns %NULL
 * if there is no active context.
 *
 */
ImContext *im_context_pop(void) {
  ImContext *ctx = context_stack;
  context_stack = context_stack->next;
  return ctx;
}

