#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef USE_NLLIBC
#include <nllibc.h>
#endif

#include "llllib.h"

static const char *p2f(const char *filename)
{
  const char *p;

  p = filename + strlen(filename);
  while (p > filename) {
    if (*(p - 1) == '/')
      break;
    p--;
  }

  return p;
}

void lll_error_print(const char *filename, int line,
		     int errcode, const char *param, int num)
{
  if (!param)
    param = "(?)";

  switch (errcode) {
  case LLL_ERRCODE_FILE_NOT_FOUND:
    fprintf(stderr, "File not found: %s\n", param);
    break;
  case LLL_ERRCODE_LESS_MEMORY:
    fprintf(stderr, "less memory: %s:%d\n", p2f(param), num);
    break;
  case LLL_ERRCODE_LESS_ARGUMENT:
    fprintf(stderr, "Less argument: %s:%d\n", p2f(param), num);
    break;
  case LLL_ERRCODE_UNKNOWN_COMMAND:
    fprintf(stderr, "Unknown command: %s:%d\n", p2f(param), num);
    break;
  case LLL_ERRCODE_UNKNOWN_OPERATOR:
    fprintf(stderr, "Unknown command: %s:%d\n", p2f(param), num);
    break;
  case LLL_ERRCODE_INVALID_FORMAT:
    fprintf(stderr, "Invalid format: %s:%d\n", p2f(param), num);
    break;

  case LLL_ERRCODE_UNKNOWN:
  default:
    fprintf(stderr, "Unknown error: (%s:%d): %s:%d\n", filename, line, param, num);
    break;
  }
}

void lll_error_exit(const char *filename, int line,
		    int errcode, const char *param, int num)
{
  lll_error_print(filename, line, errcode, param, num);
  exit(1);
}

static int finished = 0;

void lll_finished_clear(void)
{
  finished = 0;
}

void lll_finish(void)
{
  finished++;
}

int lll_is_finished(void)
{
  return (finished > 0);
}
