#include "stdafx.h"

#include "Image.hxx"

void eatComments(FILE *f)
{
	int ch;

	while((ch=getc(f))=='#') {
		char str[1000];
		fgets(str,1000,f);
	}
	ungetc(ch,f);   
};

void eatWhitespace(FILE *f)
{
	int ch=getc(f);

	while(ch==' ' || ch=='\t' || ch=='\n' || ch=='\f' || ch=='\r')
		ch=getc(f);

	ungetc(ch,f);
};

void Image::ReadPPM(char *fileName)
{
  std::cout << "reading PPM image " << fileName << std::endl;
  
  FILE *f;
  char ch;
  int width, height, colres;
  
  f = fopen(fileName,"r");
  if (f == NULL) {
    std::cerr << "could not open file " << fileName << std::endl;
    exit(1);
  }
  
  char str[1000];
  
  eatWhitespace(f);
  eatComments(f);
  eatWhitespace(f);
  fscanf(f,"%s",str);

  if (!strcmp(str,"P3")) {    
    eatWhitespace(f);
    eatComments(f);
    eatWhitespace(f);

    fscanf(f,"%d %d",&width,&height);
    if(width<=0 || height<=0) {
      std::cerr << "width and height of the image are not greater than zero in file " << fileName << std::endl;
      exit(1);
    }

    cout << "Image Res: " << width << " " << height << endl;

    resX = width;
    resY = height;

    delete [] pixel;
    pixel = new Vec3f[resX*resY];

    eatWhitespace(f);
    eatComments(f);
    eatWhitespace(f);
    fscanf(f,"%d",&colres);

    ch=0;
    while(ch!='\n')
      fscanf(f,"%c",&ch);
      
    for (int y=resY-1;y>=0;y--)
      for (int x=0;x<resX;x++) {
	int c[3];
	fscanf(f,"%d %d %d",c+0,c+1,c+2);
	(*this)[y][x] = Vec3f(c[0] / float(colres),
			      c[1] / float(colres),
			      c[2] / float(colres));
      }
 
    fclose(f);
  } else {
    std::cerr << "wrong format of file " << fileName<< std::endl;
    exit(1);
  }
};

void Image::WritePPM(char *fileName)
{
	std::ofstream file(fileName);
	file << "P3" << std::endl;
	file << resX << " " << resY << " " << 255 << std::endl;
	for (int y=resY-1;y>=0;y--) {
		for (int x=0;x<resX;x++)
			file 
			<< (int)(255.99999999 * (*this)[y][x].x) << " "
			<< (int)(255.99999999 * (*this)[y][x].y) << " "
			<< (int)(255.99999999 * (*this)[y][x].z) << " "
			<< "\t";
		file << std::endl;
		file << std::flush;
	};
};
