#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

static void readPictureData(FILE *file, unsigned short *ptrPicturesCount, unsigned short *ptrPictureWidth, unsigned short *ptrPictureHeight)
{
	unsigned int header = strlen(FILE_HEADER_STRING);

	fseek(file, header, SEEK_SET);

	fread(ptrPicturesCount, sizeof(unsigned short), 1, file);
	fread(ptrPictureWidth, sizeof(unsigned short), 1, file);
	fread(ptrPictureHeight, sizeof(unsigned short), 1, file);


}


// TODO Vervollständigen Sie die Funktion readImages unter Benutzung Ihrer Hilfsfunktionen
GrayScaleImageSeries *readImages(const char *path)
{
	unsigned short picturesCount, pictureWidth, pictureHeight;
    GrayScaleImageSeries *series = malloc(sizeof(GrayScaleImageSeries));;

    FILE *file = fopen(path,"rb");

    if (file == NULL){
        printf("failed open file\n");

        return NULL;
    }



    readPictureData(file, &picturesCount, &pictureWidth, &pictureHeight);

    series->labels = (unsigned char*)malloc(picturesCount * sizeof(char));
	series->images = (GrayScaleImage*)malloc(picturesCount * sizeof(GrayScaleImage));
    series->count = picturesCount;

    for(int i = 0; i < picturesCount; i++){
        series->images[i].width = pictureWidth;
        series->images[i].height = pictureHeight;
        series->images[i].buffer = (unsigned char*)malloc(pictureWidth * pictureHeight*sizeof(unsigned char));

        fread(series->images[i].buffer, sizeof(unsigned char), pictureWidth * pictureHeight, file);

        fread(&series->labels[i], sizeof(unsigned char), 1, file);

    }

    fclose(file);

    return series;
}

// TODO Vervollständigen Sie die Funktion clearSeries, welche eine Bildserie vollständig aus dem Speicher freigibt
void clearSeries(GrayScaleImageSeries *series)
{
    for(int i = 0; i < series->count; i++){
        free(series->images[i].buffer);
    }

    free(series->images);
    free(series->labels);
}
