// Philippos Mordohai, Stevens Institute of Technology, 2009

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
#include "ppm_lib.h"



unsigned char *read_ppm_image(char *fname, int *nx, int *ny)
{
	unsigned char *buffer;
	int i_size, x, y, s;
	ifstream fin;

	fin.open(fname, ios::binary);
	if (fin == NULL){
		cout << "File I/O error" << endl;
		exit(0);
	}

	char line[110];
	fin.getline(line,100); //read P#
	
	fin.getline(line, 5, ' ');
	
	if(line[0] >= '0' && line[0] <= '9')  // read number
		x = atoi(line);
	else
	{
		fin.getline(line, 100);  // read through comment
		fin.getline(line, 5, ' ');
		x = atoi(line);
	}
	

	fin.getline(line, 50);
	y = atoi(line);
	fin.getline(line, 50);
	s = atoi(line);

	while('\n'==fin.peek())
		fin.ignore(1);
	*nx=x; *ny=y;
	i_size=(*nx)*(*ny)*3;
	buffer = new unsigned char [i_size];
	fin.read((char *)buffer, i_size);
	fin.close();

	return(buffer);
}



int write_ppm_Uimage(unsigned char *image, char *fname, int nx, int ny)
{
	ofstream fout;

	fout.open(fname, ios::binary);
	if (fout == NULL) {
		cout << "File I/O error" << endl;
		return(0);
	}

	fout << "P6" << endl;
	fout << "# Intermediate image file" << endl;
	fout << nx << " " << ny << endl;
	fout << "255" << endl ;


    fout.write((const char *)image, 3 * nx * ny * sizeof(unsigned char));
	fout.close();
	return 1;
}


