/*
Author: <-- write your name here
Course: CSCI-135
Assignment: Lab 9

Reads the PGM image inImage.pgm into a 2-D array, copies it, and writes
the copy out as outImage.pgm. Replace the copying loop in main with your
own work; do not modify readImage or writeImage.
*/

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

const int MAX_H = 512;
const int MAX_W = 512;

void readImage(int image[MAX_H][MAX_W], int &height, int &width);
void writeImage(int image[MAX_H][MAX_W], int height, int width);

int main()
{
    int img[MAX_H][MAX_W];
    int h, w;

    readImage(img, h, w);   // h and w now hold the picture's real size

    int out[MAX_H][MAX_W];
    for (int row = 0; row < h; row++)
    {
        for (int col = 0; col < w; col++)
        {
            out[row][col] = img[row][col];
        }
    }

    writeImage(out, h, w);
    return 0;
}

// Reads the file inImage.pgm into a 2-D array.
// height and width are passed by reference: the function fills them in.
void readImage(int image[MAX_H][MAX_W], int &height, int &width)
{
    ifstream inFile("inImage.pgm");
    if (!inFile)
    {
        cout << "Error: could not open inImage.pgm" << endl;
        exit(EXIT_FAILURE);
    }

    char c;
    inFile >> c;
    inFile >> c;                                  // the "P2" magic number

    while ((inFile >> ws).peek() == '#')          // skip any comment lines
    {
        inFile.ignore(4096, '\n');
    }

    inFile >> width;
    inFile >> height;
    if (width > MAX_W || height > MAX_H)
    {
        cout << "Error: image is larger than the array" << endl;
        exit(EXIT_FAILURE);
    }

    int maxValue;
    inFile >> maxValue;

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            inFile >> image[row][col];
        }
    }
    inFile.close();
}

// Writes the first height x width elements of the array to outImage.pgm.
void writeImage(int image[MAX_H][MAX_W], int height, int width)
{
    ofstream outFile("outImage.pgm");
    if (!outFile)
    {
        cout << "Error: could not write outImage.pgm" << endl;
        exit(EXIT_FAILURE);
    }

    outFile << "P2" << endl;
    outFile << width << " " << height << endl;
    outFile << 255 << endl;

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            if (image[row][col] < 0 || image[row][col] > 255)
            {
                cout << "Error: pixel out of range at " << row << "," << col << endl;
                exit(EXIT_FAILURE);
            }
            outFile << image[row][col] << endl;
        }
    }
    outFile.close();
}
