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

#define BUFFER_SIZE 100
#define FILE_HEADER_STRING "__info2_image_file_format__"

GrayScaleImageSeries *readImages(const char *path)
{
    if (path == NULL) return NULL;

    FILE *file = fopen(path, "rb");
    if (!file) return NULL;

    // Header prüfen
    size_t tagLen = strlen(FILE_HEADER_STRING);
    if (tagLen >= BUFFER_SIZE) { fclose(file); return NULL; }

    char tagBuf[BUFFER_SIZE];
    if (fread(tagBuf, 1, tagLen, file) != tagLen || memcmp(tagBuf, FILE_HEADER_STRING, tagLen) != 0) {
        fclose(file);
        return NULL;
    }

 

    // Anzahl, Breite, Höhe lesen
    unsigned short numberOfImages = 0, width = 0, height = 0;
    if (fread(&numberOfImages, sizeof(numberOfImages), 1, file) != 1 ||
        fread(&width, sizeof(width), 1, file) != 1 ||
        fread(&height, sizeof(height), 1, file) != 1) {
        fclose(file);
        return NULL;
    }

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

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

    series->count = numberOfImages;
    series->images = calloc(series->count, sizeof(GrayScaleImage));
    series->labels = calloc(series->count, sizeof(unsigned char));
    if (!series->images || !series->labels) {
        free(series->images);
        free(series->labels);
        free(series);
        fclose(file);
        return NULL;
    }

    size_t pixelsPerImage = (size_t)width * height;
    for (unsigned int i = 0; i < series->count; i++) {
        series->images[i].width = width;
        series->images[i].height = height;
        series->images[i].buffer = malloc(pixelsPerImage * sizeof(GrayScalePixelType));
        if (!series->images[i].buffer) {
            for (unsigned int j = 0; j < i; j++) free(series->images[j].buffer);
            free(series->images);
            free(series->labels);
            free(series);
            fclose(file);
            return NULL;
        }

        if (fread(series->images[i].buffer, sizeof(GrayScalePixelType), pixelsPerImage, file) != pixelsPerImage ||
            fread(&series->labels[i], sizeof(unsigned char), 1, file) != 1) {
            for (unsigned int j = 0; j <= i; j++) free(series->images[j].buffer);
            free(series->images);
            free(series->labels);
            free(series);
            fclose(file);
            return NULL;
        }
    }

    fclose(file);
    return series;
}

void clearSeries(GrayScaleImageSeries *series)
{
    if (!series) return;
    if (series->images) {
        for (unsigned int i = 0; i < series->count; i++) {
            free(series->images[i].buffer);
        }
        free(series->images);
    }
    free(series->labels);
    free(series);
}

