#include "libpdftex.h"

char *filename = 0;
char printf_buf[PRINTF_BUF_SIZE];

void flush_printf_buf()
{
    char *p = printf_buf;
    if (sizeof(pdfbuf) - pdfptr <= PRINTF_BUF_SIZE)
        pdfflush();
    while (*p)
        pdfbuf[pdfptr++] = *p++;
}

strnumber maketexstring(char *s)
{
    int l;
    if (s == 0 || !*s)
        return getnullstr();
    l = strlen(s);
    CHECK_BUF(poolptr + l, poolsize);
    while (l-- > 0)
        strpool[poolptr++] = *s++;
    return makestring();
}

#define C_STR_BUF_SIZE  1024

char *makecstring(integer s)
{
    static char cstrbuf[C_STR_BUF_SIZE];
    char *p = cstrbuf;
    int i, l = strstart[s + 1] - strstart[s];
    CHECK_BUF(l, C_STR_BUF_SIZE);
    for (i = 0; i < l; i++)
        *p++ = strpool[i + strstart[s]];
    *p = 0;
    return cstrbuf;
}

boolean str_eq_cstr(strnumber n, char *s)
{
    int l;
    if (s == 0 || n == 0)
        return false;
    l = strstart[n];
    while (*s && l < strstart[n + 1] && *s == strpool[l])
        l++, s++;
    return !*s && l == strstart[n + 1];
}

size_t xfwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    if (fwrite(ptr, size, nmemb, stream) != nmemb)
        FAIL("fwrite() failed");
    return nmemb;
}

int xfflush(FILE *stream)
{
    if (fflush(stream) != 0)
        FAIL("fflush() failed");
    return 0;
}

int xgetc(FILE *stream)
{
    int c = getc(stream);
    if (c < 0 && c != EOF)
        FAIL("getc() failed");
    return c;
}

int xputc(int c, FILE *stream)
{
    int i = putc(c, stream);
    if (i < 0)
        FAIL("putc() failed");
    return i;
}

void libpdffinish()
{
    fm_free();
    enc_free();
    img_free();
}
