
#include "l3rt.h"

//#define FLUSH

void print_flush() {
  fflush(stdout);
}

void print_int(int i) {
  fprintf(stdout, "%d", i);
#ifdef FLUSH
  print_flush();
#endif
}

void print_char(int c) {
  fprintf(stdout, "%c", c);
#ifdef FLUSH
  print_flush();
#endif
}

void print_bool(int b) {
  if (b != 0)
    fprintf(stdout, "true");
  else
    fprintf(stdout, "false");
#ifdef FLUSH
  print_flush();
#endif
}

void print_newline() {
  fprintf(stdout, "\n");
#ifdef FLUSH
  print_flush();
#endif
}

void print_tab() {
  fprintf(stdout, "\t");
#ifdef FLUSH
  print_flush();
#endif
}

void print_space(int n) {
  int i;
  for (i = 0; i < n; i++)
    fprintf(stdout, " ");
#ifdef FLUSH
  print_flush();
#endif
}

int read_int() {
  int i;
  i = 0;
  if(!scanf("%i",&i)) {
    scanf("%*s"); // read illegal chars & discard.
  }
  return i;
}

// Allocates memory and returns a pointer to it
void* _alloc (unsigned int nbytes) {
  
  void *ret;
  
#ifdef USE_MALLOC
  if ((ret = malloc (nbytes)) == NULL) 
#else
    if ((ret = GC_MALLOC (nbytes)) == NULL)  
#endif
    {
      fprintf (stderr, "out of memory!\n");
      exit (2);
    }    
    
    return ret;
}

// The generic error-message
void _l3_error (const char *srcfile, unsigned int line,
		const char *errmsg)
{
  if (srcfile == NULL){
    if (errmsg == NULL)
      fprintf (stderr, "RUNTIME: No message\n");
    else
      fprintf (stderr, "RUNTIME: %s\n", errmsg);
  } else {
    if (errmsg == NULL)
      fprintf (stderr, "RUNTIME: %s:%d No Message\n", srcfile, line);
    else fprintf (stderr, "RUNTIME: %s:%d: %s\n", srcfile, line, errmsg);
  }

  exit(-1);
}
