#include "common.h"

#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
#include <QtGlobal>
#include <QString>


ofstream Debug("debug.log");


string
toString(const QString &s)
{
#if QT_VERSION >= 0x050000
  return s.toLatin1().constData();
#else
  return s.toAscii().constData();
#endif
}

void WriteTGA(
	      const char *aFilename,
	      const int WIDTH,
	      const int HEIGHT,
	      float *data
	      )
{
  if (data == NULL)
    return;
  
  int resX = WIDTH;
  int resY = HEIGHT;
	char header[18];
	header[0] = 0;
	header[1] = 0;
	header[2] = 2;
	header[3] = 0;
	header[4] = 0;
	header[5] = 0;
	header[6] = 0;
	header[7] = 0;
	header[8] = 0;
	header[9] = 0;
	header[10] = 0;
	header[11] = 0;
	header[12] = static_cast<uint8>(resX % 0x100);
	header[13] = static_cast<uint8>(resX / 0x100);
	header[14] = static_cast<uint8>(resY % 0x100);
	header[15] = static_cast<uint8>(resY / 0x100);
	header[16] = 24;
	header[17] = 0; // set to 32 to flip the image

	std::ofstream outFile;
	outFile.open(aFilename, std::ios::binary);
	if(!outFile) {
	  //throw std::exception("Could not open required file");
	  cerr<<"Could not open required file "<<aFilename<<endl;
	}
	
	outFile.write(reinterpret_cast<char*>(&header), 18);
	
		for(int i=0; i<(3*resX*resY);) {
		uint8 r, g, b;
		r = static_cast<uint8>(
							   std::max(0.f, std::min(1.f, data[i++])) * 255.f);
		g = static_cast<uint8>(
							   std::max(0.f, std::min(1.f, data[i++])) * 255.f);
		b = static_cast<uint8>(
							   std::max(0.f, std::min(1.f, data[i++])) * 255.f);
		outFile.write(reinterpret_cast<char*>(&b), sizeof(uint8));
		outFile.write(reinterpret_cast<char*>(&g), sizeof(uint8));
		outFile.write(reinterpret_cast<char*>(&r), sizeof(uint8));
	}
	outFile.flush();
	outFile.close();
}
