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

void *GC_malloc(int size);

typedef struct {int size; char chars[1];} *string;

void print_int(int x)
{
  printf("%d",x);
  return;
}

void print_string(string s)
{
  fwrite(s->chars, 1, s->size, stdout);
}

void print_newline(void)
{
  putchar('\n');
}

int int_of_string(string s)
{
  int n, i, sign=1;
  for(i=0; i<s->size && isspace(s->chars[i]); i++);
  while (i<s->size &&(s->chars[i]=='-' || s->chars[i]=='+')) {
    if (s->chars[i]=='-') sign=-sign;
    i++;
  }
  if (i==s->size) {
    fprintf(stderr, "\ninvalid string to integer conversion\n");
    exit(2);
  }
  for(n=0; i<s->size; i++) {
    char c=s->chars[i];
    if ('0'<=c && c<='9')
      n=n*10+(int)(c-'0');
    else {
      fprintf(stderr, "\ninvalid string to integer conversion\n");
      exit(2);
    }
  }
  return sign*n;
}

string string_of_int(int n)
{
  string str=GC_malloc(16);
  sprintf(str->chars, "%d", n);
  str->size=strlen(str->chars);
  return str;
}

/*****************************************************************************
 * Timer declarations and functions
 *   int_time() returns a 32 bits of msecs since ?/?/1970
 ****************************************************************************/

typedef long time_t;
struct _timeb {
        time_t time;
        unsigned short millitm;
        short timezone;
        short dstflag;
        };

int int_time()
{
  struct _timeb tstr;
  long result;

  /* places secs in "time field", msecs in "millitm" field */
  _ftime( &tstr );
  
  /* get secs */
  result = tstr.time;

  /* free up top ten 10 bits (to avoid overflow of following multiplication) */
  result = result & 0x003fffff;

  /* convert from secs to msecs (now uses all 32 bits) */
  result = result * 1000;
  
  /* add in msecs */
  result = result + tstr.millitm;

  return result;
}

void print_time(int start_time, int end_time, int iterations)
{
  printf("Time: %d msec\n", (end_time - start_time) / iterations);
}

/*****************************************************************************
 * Functions useful for debugging
 ****************************************************************************/

void get_input(string out)
{
  char c;


  print_string(out);
  printf("(Hit <RETURN> to continue, 'q' + <RETURN> to quit)");
  fflush(stdout);
  c = getchar();

  if (c == 'q')
    exit(0);
}

void flush_stdout()
{
  fflush(stdout);
}

/* EOF: stdlib.c */
