/* bitmap_8bit.c
 *
 * ToDo (and to test!):
 * - set- and getPixel to macros
 */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


#include "def.h"
#include "bitmap_8bit.h"



/*
 * LOCAL functions
 */

static int isValidCoords(Bitmap_8bit *bitmap, int x, int y) {
  return ( (0 <= x && x < bitmap->width ) &&
	   (0 <= y && y < bitmap->height)    );
}

/*
 * PUBLIC functions
 */

Bitmap_8bit * create_bmp8bit(int width, int height) {
  Bitmap_8bit *bitmap;

  bitmap = malloc( sizeof(Bitmap_8bit) );
  if(bitmap == NULL) {
    return NULL;
  }
  bitmap->width  = width;
  bitmap->height = height;
  
  bitmap->image = calloc(width*height, sizeof(unsigned char) );
  if( bitmap->image == NULL ) {
    free(bitmap);
    return NULL;
  }

  return bitmap;
}

void setPixel_bmp8bit(Bitmap_8bit *bitmap,
		      int x, int y, unsigned char value) {
  unsigned char *p;
  
  assert(isValidCoords(bitmap, x, y));

  p = bitmap->image + (y * bitmap->width) + x;
  *p = value;
}


unsigned char getPixel_bmp8bit(Bitmap_8bit *bitmap,
			       int x, int y) {
  
  unsigned char *p;
  
  assert( isValidCoords(bitmap, x, y) );

  p = bitmap->image + (y * bitmap->width) + x;
  return *p;
}

int writeToFile_bmp8bit(Bitmap_8bit *bitmap, char *filename) {
  FILE *file;
  int i;
  size_t length;
  
  file = fopen(filename, "w");
  if(file == NULL) {
    perror( filename );
    return FALSE;
  }
    
  /* Header information */
  fprintf(file,"P5\n %d %d\n 255\n",bitmap->width,bitmap->height);
  
  length = bitmap->width * bitmap->height;
  i = fwrite(bitmap->image, sizeof(unsigned char), length, file);  

  fclose(file);

  return TRUE;
}

/*
 * PENDING!
 * Korjaa nämä käyttämään libpgm:ää ! Jossa on valmiit funkkarit headerin 
 * ja datan lukemiseen !                   Teemu Kurppa 22.2.2000
 */

static int isCorrectFileType(FILE *file) {
  char type[3];
  fscanf(file, "%s", type);
  return (type[0] == 'P' && type[1] == '5');
}


static int readDimensions(FILE *file, int *width, int *height, int *depth) {
  return fscanf(file, "%d %d %d", width, height, depth);
}
	
      
Bitmap_8bit * readFromFile_bmp8bit(char *filename) {
  FILE *file;
  int width, height, depth;
  int i, value;
  Bitmap_8bit *bitmap;


  file = fopen(filename, "r");
  if(file == NULL) {
    perror( filename );
    return NULL;
  }
  
  if( ! isCorrectFileType(file) ) {
    fclose(file);
    return NULL;
  }
    
  if( readDimensions(file, &width, &height, &depth) != 3) {
    fclose(file);
    return NULL;
  }

  /* Jump over last newline */
  fseek(file, 1, SEEK_CUR);
  
  bitmap = create_bmp8bit(width, height);
  if(bitmap == NULL) {
    fclose(file);
    return NULL;
  }

  i = 0;
  while( (value = fgetc(file)) != EOF) {
    bitmap->image[i] = (unsigned char) value;
    i++;
  }
  
  fclose(file);
  
  return bitmap;
}  

					 



      
