/*
    libc.c - Internal library functions for Little C interpreter

    Herbert Schildt
    Dr. Dobb's Journal v14, n8, August 1989
    http://www.ddj.com/184408184
*/

/*#include <conio.h>*/  /* if your compiler does not
                       support this  header file,
                       remove it */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "littlec.h"

extern char *prog; /* points to current location in program */
extern char token[TOK_SIZE]; /* holds string representation of token */
extern char token_type; /* contains type of token */
extern char tok; /* holds the internal representation of token */

/* Get a character from console. (Use getchar() if
   your compiler does not support _getche().) */
int call_getche()
{
    char ch;
    /* ch = _getche(); */
    ch = getchar();
    while(*prog!=')') prog++;
    prog++;   /* advance to end of line */
    return ch;
}

/* Put a character to the display. */
int call_putch()
{
    int value;

    eval_exp(&value);
    printf("%c", value);
    return value;
}

/* Call puts(). */
int call_puts(void)
{
    get_token();
    if (*token!='(') sntx_err(PAREN_EXPECTED);
    get_token();
    if (token_type!=STRING) sntx_err(QUOTE_EXPECTED);
    puts(token);
    get_token();
    if (*token!=')') sntx_err(PAREN_EXPECTED);

    get_token();
    if (*token!=';') sntx_err(SEMI_EXPECTED);
    putback();
    return 0;
}

/* A built-in console output function. */
int print(void)
{
    int i;

    get_token();
    if (*token!='(')  sntx_err(PAREN_EXPECTED);

    get_token();
    if (token_type==STRING) { /* output a string */
        printf("%s ", token);
    }
    else {  /* output a number */
        putback();
        eval_exp(&i);
        printf("%d ", i);
    }

    get_token();

    if (*token!=')') sntx_err(PAREN_EXPECTED);

    get_token();
    if (*token!=';') sntx_err(SEMI_EXPECTED);
    putback();
    return 0;
}

/* Read an integer from the keyboard. */
int getnum(void)
{
    char s[STRING_SIZE];

    fgets(s,STRING_SIZE,stdin);
    while(*prog != ')') prog++;
    prog++;  /* advance to end of line */
    return atoi(s);
}

/* Sleep for the specified period. */
int call_sleep()
{
    int value;

    eval_exp(&value);
    sleep(value);
    return 0;
}
