#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

// TODO Vervollständigen Sie die Funktion readImages unter Benutzung Ihrer Hilfsfunktionen
GrayScaleImageSeries *readImages(const char *path)
{
    FILE *file = fopen(path, "rb");
    if (!file) return NULL;

    fseek(file, strlen("__info2_image_file_format__"), SEEK_SET);

    unsigned short anzahlBilder, width, height;
    fread(&anzahlBilder, sizeof(unsigned short), 1, file);
    fread(&width, sizeof(unsigned short), 1, file);
    fread(&height, sizeof(unsigned short), 1, file);

    GrayScaleImageSeries *series = malloc(sizeof(GrayScaleImageSeries));
    if (!series) { 
        fclose(file); 
        return 0;
     }

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

    int pixelCount = width * height;

    for (unsigned int i = 0; i < anzahlBilder; i++)
    {
        series->images[i].width = width;
        series->images[i].height = height;
        series->images[i].buffer = malloc(pixelCount);

        fread(series->images[i].buffer, 1, pixelCount, file);
        fread(&series->labels[i], 1, 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)
{
    if (series == NULL)
        return 0;

   
    for (unsigned int i = 0; i < series->count; i++)
    {
        free(series->images[i].buffer);
        series->images[i].buffer = NULL;
    }

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

    series->images = NULL;
    series->labels = NULL;

    
    free(series);
}
