/* PGM loader */

#include<stdlib.h>
#include<string.h>


#define MAX_IMAGESIZE       1800
#define MAX_BRIGHTNESS       255
#define GRAYLEVEL            256
#define MAX_FILENAME         256
#define MAX_BUFFERSIZE       256

// unsigned char image[MAX_IMAGESIZE][MAX_IMAGESIZE];
unsigned char image[MAX_IMAGESIZE*MAX_IMAGESIZE];

int width, height;

void load_image( int n, FILE *fp );
void save_image( int n, FILE *fp );
void copy_image( int n1, int n2 );
void init_image( int n, unsigned char value );
void load_image( int n, FILE *fp )
{
    char buffer[MAX_BUFFERSIZE];
    int max_gray;
    int x, y;

    fgets( buffer, MAX_BUFFERSIZE, fp );
    if ( buffer[0] != 'P' || buffer[1] != '5' ){
        printf("Not P5 PGM file.\n");
        exit(1);
    }

    width = 0;    height = 0;
    while ( width == 0 || height == 0 ){
        fgets( buffer, MAX_BUFFERSIZE, fp );
        if ( buffer[0] != '#' )
            sscanf( buffer, "%d %d", &width, &height );
    }

    max_gray = 0;
    while ( max_gray == 0 ){
        fgets( buffer, MAX_BUFFERSIZE, fp );
        if ( buffer[0] != '#' )
            sscanf( buffer, "%d", &max_gray );
    }
    printf("Width = %d, Height = %d\n", width, height );
    printf("Max gray = %d\n",max_gray);
    if ( width > MAX_IMAGESIZE || height > MAX_IMAGESIZE ){
        printf("Error width or height greater than %d x %d ．\n", 
            MAX_IMAGESIZE, MAX_IMAGESIZE);
        exit(1);
    }
    if ( max_gray != MAX_BRIGHTNESS ){
        printf("Error: max_gray != MAX_BRIGHTNESS  \n");  exit(1);
    }
    for(y=0;y<height;y++)
        for(x=0;x<width;x++)
//            image[x][y] = (unsigned char)fgetc( fp );
            image[y * width + x] = (unsigned char)fgetc( fp );
}

#if 0
void save_image( int n, FILE *fp )
{
    int x, y;

    fputs( "P5\n", fp );
    fputs( "# Created by Rafael Diniz\n", fp );
    fprintf( fp, "%d %d\n", width[n], height[n] );
    fprintf( fp, "%d\n", MAX_BRIGHTNESS );
    for(y=0;y<height[n];y++)
        for(x=0;x<width[n];x++)
            fputc( image[n][x][y], fp );

}

void copy_image( int n1, int n2 )
{
    int x, y;

    width[n2] = width[n1];    height[n2] = height[n1];

    for(y=0;y<height[n1];y++)
        for(x=0;x<width[n1];x++)
            image[n2][x][y] = image[n1][x][y];
}

void init_image( int n, unsigned char value )
{
    int x, y;

    for(y=0;y<height[n];y++)
        for(x=0;x<width[n];x++)
            image[n][x][y] = value;
}
#endif
