#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

//Hilfsfunktion Header prüfen
static int checkHeader(FILE *file) {
    char buffer[100];
    if (fgets(buffer, sizeof(buffer), file) == NULL)
        return 0;

    buffer[strcspn(buffer, "\r\n")] = 0;
    return strcmp(buffer,FILE_HEADER_STRING ) == 0;
}

//Hilfsfkt. 2 Bytes als unsigned short lesen (littel Endian)
static unsigned short readUShort(FILE *file) {
    unsigned char bytes[2];
    fread(bytes, 1, 2, file);
    return (bytes[1] << 8) | bytes[0];  // Little Endian
}


// 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;

    if (!checkHeader(file)) {
        fclose(file);
        return NULL;
    }

    unsigned short count  = readUShort(file);
    unsigned short width  = readUShort(file);
    unsigned short height = readUShort(file);

    if (count == 0 || width == 0 || height == 0) {
    fclose(file);
    return NULL;
}

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

    series->count  = count;
    series->labels = malloc(count * sizeof(unsigned char));
    series->images = malloc(count * sizeof(GrayScaleImage));
    if (!series->labels || !series->images) {
        fclose(file);
        free(series->labels);
        free(series->images);
        free(series);
        return NULL;
    }
for (unsigned int i = 0; i < count; i++) {
        GrayScaleImage *img = &series->images[i];
        img->width  = width;
        img->height = height;
        img->buffer = malloc(width * height * sizeof(GrayScalePixelType));
        if (!img->buffer) {
            fclose(file);
            clearSeries(series);
            return NULL;
        }

        if (fread(img->buffer, sizeof(GrayScalePixelType), width * height, file) != width * height) {
            fclose(file);
            clearSeries(series);
            return NULL;
        }

        if (fread(&series->labels[i], sizeof(unsigned char), 1, file) != 1) {
            fclose(file);
            clearSeries(series);
            return NULL;
        }
    }

    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) return;
    for (unsigned int i = 0; i < series->count; i++) {
        free(series->images[i].buffer);
    }
    free(series->images);
    free(series->labels);
    free(series);
}
