#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "imageInput.h"

#define BUFFER_SIZE 100
#define FILE_HEADER_STRING "__info2_image_file_format__"

// TODO Implementieren Sie geeignete Hilfsfunktionen für das Lesen der Bildserie aus einer Datei

int checkHeader(FILE* fileName)
{
  char buffer[BUFFER_SIZE];
  fread(buffer,sizeof(char),strlen(FILE_HEADER_STRING),fileName);
  buffer[strlen(buffer)]='\0';
  if(strncmp(buffer,"__info2_image_file_format__",strlen(FILE_HEADER_STRING)) != 0)
    return 0;
 return 1;

}
//// TODO Vervollständigen Sie die Funktion readImages unter Benutzung Ihrer Hilfsfunktionen
GrayScaleImageSeries *readImages(const char *path)
{
  	 FILE* file = fopen(path,"rb");
    unsigned int width=0,height=0;
	GrayScaleImageSeries *imageSeries = malloc(sizeof(GrayScaleImageSeries));
    imageSeries->count = 0;
    if(checkHeader(file) == 0) {
        fclose(file);
        return NULL;
    }
    fread(&imageSeries->count,sizeof(unsigned short),1,file);
    imageSeries->images = malloc(imageSeries->count * sizeof(GrayScaleImage));
    fread(&width,sizeof(unsigned short),1,file);
    fread(&height,sizeof(unsigned short),1,file);
    imageSeries->labels = malloc(imageSeries->count * sizeof(unsigned char));
    for(int i = 0; i < imageSeries->count; i++) {
       imageSeries->images[i].width = width;
        imageSeries->images[i].height = height;
       const unsigned int imageSize = height*width;
        imageSeries->images[i].buffer = malloc(imageSize*sizeof(GrayScalePixelType));
        for (int j=0;j<imageSize;j++)
        {
            fread(&imageSeries->images[i].buffer[j],sizeof(GrayScalePixelType),1,file);
        }
        fread(&imageSeries->labels[i],sizeof(unsigned char),1,file);
     }

    return imageSeries;
}

// TODO Vervollständigen Sie die Funktion clearSeries, welche eine Bildserie vollständig aus dem Speicher freigibt
void clearSeries(GrayScaleImageSeries *series)
{
    free(series->images);
    free(series->labels);
    free(series);
}