/* Read one 8-bit binary PPM (P6); write grayscale and Sobel PGM (P5).
   Supports header comments and images up to 4096 x 4096 pixels.
   Usage: ./image_demo sample.ppm grayscale.pgm edges.pgm */
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int token(FILE *fp, char *out, size_t size) {
    int c;
    do {
        c = fgetc(fp);
        if (c == '#') while (c != '\n' && c != EOF) c = fgetc(fp);
    } while (c != EOF && isspace((unsigned char)c));
    size_t n = 0;
    while (c != EOF && !isspace((unsigned char)c) && c != '#') {
        if (n + 1 >= size) return 0;
        out[n++] = (char)c;
        c = fgetc(fp);
    }
    if (c != EOF) ungetc(c, fp);
    out[n] = '\0';
    return n != 0;
}

static int header_number(FILE *fp, int limit) {
    char text[32], *end;
    if (!token(fp, text, sizeof text)) return 0;
    /* A bounded decimal parser avoids conversion overflow. */
    int value = 0;
    for (end = text; *end; ++end) {
        if (*end < '0' || *end > '9') return 0;
        int digit = *end - '0';
        if (value > (limit - digit) / 10) return 0;
        value = value * 10 + digit;
    }
    return value > 0 && value <= limit ? value : 0;
}

static unsigned char *read_ppm(const char *path, int *w, int *h) {
    FILE *fp = fopen(path, "rb");
    if (!fp) { perror(path); return NULL; }
    char magic[8];
    unsigned char *rgb = NULL;
    if (!token(fp, magic, sizeof magic) || strcmp(magic, "P6") != 0) goto fail;
    *w = header_number(fp, 4096);
    *h = header_number(fp, 4096);
    if (!*w || !*h || header_number(fp, 255) != 255) goto fail;
    /* P6 has one whitespace separator before the binary raster. */
    int separator = fgetc(fp);
    if (separator == EOF || !isspace((unsigned char)separator)) goto fail;
    if (separator == '\r') {
        int next = fgetc(fp);
        if (next != '\n' && next != EOF) ungetc(next, fp);
    }
    size_t bytes = (size_t)*w * (size_t)*h * 3;
    rgb = malloc(bytes);
    if (!rgb || fread(rgb, 1, bytes, fp) != bytes) goto fail;
    fclose(fp);
    return rgb;
fail:
    fprintf(stderr, "%s: expected a complete P6 image, maxval 255, up to 4096 x 4096.\n", path);
    free(rgb);
    fclose(fp);
    return NULL;
}

static int write_pgm(const char *path, int w, int h, const unsigned char *pixels) {
    FILE *fp = fopen(path, "wb");
    if (!fp) { perror(path); return 0; }
    size_t size = (size_t)w * (size_t)h;
    int ok = fprintf(fp, "P5\n%d %d\n255\n", w, h) > 0;
    if (ok) ok = fwrite(pixels, 1, size, fp) == size;
    if (fclose(fp) != 0) ok = 0;
    if (!ok) fprintf(stderr, "Could not write %s\n", path);
    return ok;
}

int main(int argc, char **argv) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s input.ppm grayscale.pgm edges.pgm\n", argv[0]);
        return 1;
    }
    if (!strcmp(argv[1], argv[2]) || !strcmp(argv[1], argv[3]) || !strcmp(argv[2], argv[3])) {
        fputs("Choose three different file paths.\n", stderr);
        return 1;
    }
    int w, h;
    unsigned char *rgb = read_ppm(argv[1], &w, &h);
    if (!rgb) return 1;
    size_t n = (size_t)w * (size_t)h;
    unsigned char *gray = malloc(n);
    unsigned char *edges = calloc(n, 1); /* Border pixels remain black. */
    if (!gray || !edges) {
        fputs("Not enough memory.\n", stderr);
        free(rgb); free(gray); free(edges);
        return 1;
    }
    for (size_t i = 0; i < n; ++i) {
        gray[i] = (unsigned char)((299u * rgb[3*i] + 587u * rgb[3*i+1] + 114u * rgb[3*i+2]) / 1000u);
    }
    const int gx[3][3] = {{-1,0,1},{-2,0,2},{-1,0,1}};
    const int gy[3][3] = {{-1,-2,-1},{0,0,0},{1,2,1}};
    for (int y = 1; y < h - 1; ++y) {
        for (int x = 1; x < w - 1; ++x) {
            int sx = 0, sy = 0;
            for (int dy = -1; dy <= 1; ++dy) {
                for (int dx = -1; dx <= 1; ++dx) {
                    int v = gray[(size_t)(y + dy) * (size_t)w + (size_t)(x + dx)];
                    sx += v * gx[dy+1][dx+1];
                    sy += v * gy[dy+1][dx+1];
                }
            }
            double magnitude = sqrt((double)sx * sx + (double)sy * sy);
            edges[(size_t)y * (size_t)w + (size_t)x] = (unsigned char)(magnitude > 255 ? 255 : magnitude);
        }
    }
    int ok = write_pgm(argv[2], w, h, gray) && write_pgm(argv[3], w, h, edges);
    if (ok) printf("%d x %d: wrote %s and %s\n", w, h, argv[2], argv[3]);
    free(rgb); free(gray); free(edges);
    return ok ? 0 : 1;
}
