#include "Canvas.h"
#include "color.h"
#include "xcplusplus.h"

#include <vector>
#include <algorithm>



void Canvas :: init() 
{ 
  int N = hReso*vReso;
    
  delete [] rgbs; 
  rgbs = new RGB [N]; 
  fill( rgbs, rgbs + N, RGB(0.0, 0.0, 0.0) );
}
  


void Canvas :: WritePPM(const char *_filename) const
{
  Canvas* This =  (Canvas*)this;
    
  if(!_filename) 
    _filename = filename.c_str();

  ofstream file;
  file.open (_filename, ios::out | ios::binary);
    
  if(file) 
  {
    file << "P6\n";   // color rawbits format
    file << hReso << " " << vReso << endl << 100 << endl;
  
    unsigned char r, g, b;
    for (int row = vReso-1; row >= 0; row--) 
      for (int col = 0; col < hReso; col++) 
      {
	RGB& c = This->pixel(row, col);
	
	if(c[0] < 0 || c[1] < 0 || c[2] < 0)
	  throw "RGB color underflow\n"; 
	if(c[0] > 1.0 || c[1] > 1.0 || c[2] > 1.0)
	  throw "RGB color overflow\n"; 

	r = (unsigned char) (100.0 * c[0]);  
	g = (unsigned char) (100.0 * c[1]);  
	b = (unsigned char) (100.0 * c[2]);  

	file << r << g << b;
      }

    file << endl;
    file.close();
  }
  else 
    cerr << "Can't open output file " << _filename << endl;
}
  

void Canvas :: ReadPPM(const string& filename)
{
  ifstream file;
  file.open (filename.c_str(), ios::in | ios::binary);
    
  if(file) 
  {
    string id;
      
    skip_comment_lines(file, '#');

    file >> id;

    if(id != "P6") throw "not P6 ppm format\n";   // color rawbits format

    float scale;
    skip_comment_lines(file, '#');
    file >> hReso >> vReso;
    skip_comment_lines(file, '#');
    file >> scale;

    init();
    unsigned char r, g, b;
    file >> noskipws >> r;
      
    for (int row = vReso-1; row >= 0; row--) 
    {
      for (int col = 0; col < hReso; col++) 
      {
	file >> noskipws >> r >> noskipws >> g >> noskipws >> b;
	pixel(row, col)[0] = r / scale;  
	pixel(row, col)[1] = g / scale;  
	pixel(row, col)[2] = b / scale;  
      }
    }
      
    file.close();
  }
  else 
    cerr << "Can't open input file " << filename << endl;
}



