#include <fstream>
#include <string>
#include <iostream>

#include "pnm.h"

using namespace std;

namespace pnm
{

  bool read_header(std::ifstream& istr, Format& type, unsigned int& width, unsigned int& height)
  {
    // check magic
    if (istr.get() != 'P' )
    {
      return false;
    }

    char c_type = static_cast<char>(istr.get());
    if (c_type == '6')
    {
      type = Format::PPM;
    }
    else if (c_type == '5')
    {
      type = Format::PGM;
    }
    else
    {
      cerr << "Invalid PNM format." << endl;
      return false;
    }

    if (istr.get() != '\n')
    {
      return false;
    }

    // skip comments
    while (istr.peek() == '#')
    {
      std::string line;
      std::getline(istr, line);
    }

    // get size
    istr >> width >> height;
    if (width == 0 || height == 0)
    {
      return false;
    }

    // get maxvalue
    if (istr.get() != '\n')
    {
      return false;
    }

    int max_value = -1;
    istr >> max_value;
    if (max_value > 255)
    {
      return false;
    }

    if (istr.get() != '\n')
    {
      return false;
    }

    return true;
  }

  bool write_header(std::ofstream& ostr, Format type, unsigned int width, unsigned int height)
  {
    if (type == Format::PGM)
      ostr << "P5" << endl;
    if (type == Format::PPM)
      ostr << "P6" << endl;
    ostr << width << " " << height << endl;
    ostr << "255" << endl;
    return true;
  }

} // end of namespace pnm
