#include "ninox.h"

// This defines FONT_WIDTH, FONT_HEIGHT and FontMap[]
// source font data
#include "font_7x14.c"

// This defines the output cell size on our image
#define Font_Width 8
#define Font_Height 16

// Set the named pixel to white
static inline void
SetBlackPixel(struct Image *img, int y, int x)
        {
        if (y < 0 || x < 0 || y >= img->height || x >= img->width)
           return;

        if (img->depth == 8)
           *((unsigned char *)img->data + y * img->width + x) = 0;

        if (img->depth == 16)
           *((unsigned short *)img->data + y * img->width + x) = 0;

        if (img->depth == 32)
           *((unsigned int *)img->data + y * img->width + x) = 0;
        }

// Set the named pixel to white
static inline void
SetWhitePixel(struct Image *img, int y, int x)
        {
        if (y < 0 || x < 0 || y >= img->height || x >= img->width)
           return;

        if (img->depth == 8)
           *((unsigned char *)img->data + y * img->width + x) = 0xff;

        if (img->depth == 16)
           *((unsigned short *)img->data + y * img->width + x) = 0xffff;

        if (img->depth == 32)
           *((unsigned int *)img->data + y * img->width + x) = 0xffffffff;
        }

static int
DrawChar(struct Image *img, int y, int x, int ch, int flags)
        {
        if (ch>=32 && ch < 128) {
           int i,r,c;
           unsigned short *uptr = FontMap + (unsigned short)ch * FONT_HEIGHT;
           unsigned short mask;

           for(r=0; r<Font_Height; ++r, ++uptr) {
                for(c=0,mask=1; c<Font_Width; ++c,mask<<=1) {
                   if (*uptr & mask)
			SetWhitePixel(img,y+r,x+c);
		   else if (flags & DRAW_BLACK_PIXELS)
                        SetBlackPixel(img,y+r,x+c);
		   }
	 	}

           return 1;
           }

        return 0;
        }

int
DrawString(struct Image *img, int y, int x, char *str, int flags)
        {
        int nchars=0;
        int i,len;
        int max_x = img->width - Font_Width;

        len = strlen(str);
        for(i=0; i<len; ++i, x += Font_Width) {
           if (x <= max_x)
              nchars += DrawChar(img,y,x,str[i],flags);
           }

        return nchars;
	}
