/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished proprietary information of BroadOn Communications Corp.,
 *  and are protected by federal copyright law. They may not be disclosed
 *  to third parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 *  Description:
 *      This file implements standard IO functions using semi-hosting
 *
 */


#include <stdarg.h>
#include <ioslibc.h>
#include <vio.h>
#include "printf.h"

#define BUF_SIZE 16

typedef struct {
    Context v;
    char buf[BUF_SIZE];
    unsigned int pos;
    int total;
} IoContext;

static void __ioFlush(Context *ctx)
{
    IoContext *ioctx = (IoContext *)ctx;
    if (ioctx->pos) {
        ioctx->buf[ioctx->pos] = 0;
        ioctx->pos = 0;
        __sys_write0(ioctx->buf);
    }
}

static void __ioWritec(Context *ctx, char c)
{
    IoContext *ioctx = (IoContext *)ctx;
    ioctx->buf[ioctx->pos++] = c;
    ++ioctx->total;
    if (ioctx->pos == BUF_SIZE-1) {
        ctx->flush(ctx);
    }
}

int
vprintf(const char *fmt, va_list ap)
{
    IoContext ctx;
    ctx.pos = ctx.total = 0;
    ctx.v.writec = __ioWritec;
    ctx.v.flush = __ioFlush;
    __printf((Context *)&ctx, fmt, ap);
    return ctx.total;
}

int
printf(const char *fmt, ...)
{
    va_list ap;
    int rv;

    va_start(ap, fmt);
    rv = vprintf(fmt, ap);
    va_end(ap);

    return rv;
}
