/*
 * Image.cpp
 *
 *  Created on: Mar 15, 2011
 *      Author: cpresser
 */

#include "PGMImage.h"

#include <fstream>

PGMImage::PGMImage(int w, int h):
                m_width(w),
                m_height(h)
{
        m_data = new pixel[w*h];
}

//copy constructor
PGMImage::PGMImage(const PGMImage &image):
                m_width(image.m_width),
                m_height(image.m_height)
{
        int length = m_width*m_height;
        m_data = new pixel[length];

        //copy the array
        for(int i = 0; i < length; i++){
                m_data[i] = image.m_data[i];
        }
}

PGMImage::~PGMImage() {
        delete[] m_data;
}

const PGMImage &PGMImage::operator=(const PGMImage &image){

        //avoid self assignment issues
        if(&image != this){
                int newLength = image.m_width * image.m_height;
                int oldLength = m_width * m_height;

                //Do we have the wrong amount allocated already?
                if(newLength != oldLength){
                        delete[] m_data;
                        m_data = new pixel[newLength];
                }
                m_width = image.m_width;
                m_height = image.m_height;
                for(int i = 0; i < newLength; i++){
                        m_data[i] = image.m_data[i];
                }
        }

        return *this;
}

pixel PGMImage::getPixel(int x, int y) throw (PGMImageException){
         int index = posToIndex(x, y);
         return m_data[index];
}

 void PGMImage::setPixel(int x, int y, pixel p) throw (PGMImageException) {

         int index = posToIndex(x, y);

         m_data[index] = p;
 }

 void PGMImage::writeToFile(std::string name){
         std::ofstream out2file;
         out2file.open(name.c_str(), std::ofstream::binary);

         out2file << "P5\n";
         out2file << m_width << " " << m_height << "\n";
         out2file << "255\n";


         int next = 0;
         for(int i = 0; i < m_height; i++){
                 for(int j = 0; j < m_width; j++){
                         out2file << m_data[next];// << " ";
                         next++;
                 }
                 //out2file << "\n";
         }

         out2file.close();

 }


 int PGMImage::posToIndex(int x, int y) throw (PGMImageException) {
         if(x < 0 || x >= m_width || y < 0 || y >= m_height){
                 //ERROR!
                 PGMImageException exp;
                 throw exp;
         }
         return y * m_width + x;
 }