#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))

// Read grayscale file with comment
int IPReadGrayCom (char *filename, BYTE* img, int comment)  // Read PNM file, fill/crop if req.
{   char next, code[100];
    int  codecount[4] = {0, 1, 1, 3};  /* 1 byte for PBM, PGM, 3 bytes for PPM */
    int  codenum, ascii, width, height, levels, count = 0;
    int  maxheight, maxwidth;
    FILE *fp = fopen(filename, "r");

    if (fp == NULL) { printf("!error: read file\n"); return -1;}

    fscanf(fp, "%s", code);
    codenum = (int) (code[1] - '0'); // make into an integer
    printf("image code %d\n",codenum);
    ascii = codenum<4;  /* P1,2,3 are ASCII, P4,5,6 are binary */
    if (!ascii) codenum = codenum - 3;  //reduce to 1..3
    
    if (codenum !=2 || ascii) return -1; // erroe
    //if (codenum<1 || codenum>3) { printf("bad image code\n"); return -1;}
    do next = fgetc(fp);  // clear white space
    while (next=='\n' || next==' ');

    if (next=='#')  /* read comment */
      fscanf(fp, "%d", &comment);
    else return -2; // error, no comment entry

    fscanf(fp, "%d %d", &width, &height);
    if (codenum>1) fscanf(fp, "%d", &levels);
    if (!img) return width*height*codecount[codenum];
    printf("Read %s file %s: W%d H%d\n", code, filename, width, height);
    next = fgetc(fp);  // simulator only
    /*do next = fgetc(fp);  // clear white space
    while (next=='\n' || next==' ');
    ungetc(next, fp);  // give character back
    */
    
    // PGM (gray), PPM (color)
    { maxwidth  = MAX(width,  IP_WIDTH);
        maxheight = MAX(height, IP_HEIGHT);
        for (int i=0; i<maxheight; i++)
        { for (int j=0; j<maxwidth; j++)
                { if (i<MIN(IP_HEIGHT,height) && j<MIN(IP_WIDTH,width))  // read image
                    { img[count++] = fgetc(fp);
                    }
                    else if (j>=IP_WIDTH || i>=IP_HEIGHT) fgetc(fp);  // read pixels beyond parameter size
                    else if (j>=width || i>=height) img[count++] = 0;  // fill remaining area with black pixels
                }
        }
    }
    fclose(fp);
    return 0; 
}


// Write gray image to PGM file with integer comment
int IPWriteFileGrayCom(char *filename, BYTE* img, int comment)  // Write gray scale PGM file
{
    FILE *fp = fopen(filename, "w");
    if (fp == NULL) { printf("error: write file\n"); return -1;}
    //P5 = binary, P2 = ascii
    fprintf(fp, "P5\n# %d\n%d %d\n255\n", comment, IP_WIDTH,IP_HEIGHT);
    for (int i=0; i<IP_PIXELS; i++) fputc(img[i], fp);
    fprintf(fp,"\n");
    fclose(fp);
    return 0;
}

