#include <stdio.h>
#include "ttf2pk.h"
#include "ttf.h"
#include "font.h"
#include "error.h"

/*
   ppem = pixel per EM (character metric)
   res  = pixel per inch
   dpoint= font size in point (1 point = 1/72 inch)
           dpoint
   ppem =  ------ * res
             72
*/

BITMAP * BITMAP_Init(double point,int res,int mode)
{
  BITMAP *b;
  USHORT ppem;

  b = TTFALLOC(BITMAP);
  if (b == NULL)
    return NULL;
  ppem = point * res / 72;
  b->xpoint = ppem;
  b->xsize = (ppem+7)/8;
  b->ysize = ppem;
  b->point = point;
  b->res = res;
  b->mode = mode;
  BITMAP_color(b,1);
  b->map = (char *) malloc(b->xsize*b->ysize);
  if (b->map==NULL)
  {
    Error_throw(error_out_of_memory);
    return NULL;
  }
  return b;
}

void BITMAP_color(BITMAP *bit,int color)
{
  int i;

  switch(bit->mode)
  {
  case BITMAP_ONE_BIT:
    if (color)
      bit->color = 0xffff;
    else
      bit->color = 0;
    bit->xsize = (bit->xpoint +7)/8;
    break;
  case BITMAP_TWO_BIT:
    color &= 0x3;
    bit->color=color;
    for(i=0;i<4;i++)
    {
      color <<=2;
      bit->color |= color;
    }
    bit->xsize = (bit->xpoint+3)/4;
    break;
  case BITMAP_FOUR_BIT:
    color &=0xf;
    bit->color = color;
    bit->color |= (color<<4);
    bit->xsize = (bit->xpoint+1)/2;
    break;
  case BITMAP_ONE_BYTE:
    color &=0xff;
    bit->color=color;
    bit->xsize = bit->xpoint;
    break;
  case BITMAP_TWO_BYTES:
    color &= 0xffff;
    bit->color=color;
    bit->color|=(color<<16);
    bit->xsize = bit->xpoint*2;
    break;
  case BITMAP_THREE_BYTES:
    color &= 0xffffff;
    bit->color = color;
    bit->xsize = bit->xpoint*3;
    break;
  case BITMAP_FOUR_BYTES:
    bit->color = color;
    bit->xsize = bit->xpoint*4;
    break;
  }
}

void BITMAP_done(BITMAP *bit)
{
  if (bit->map)
  free(bit->map);
  free(bit);
}
