#ifndef __COMMON_H
#define __COMMON_H

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string>
#include <fstream>
#include <math.h>

class QString;

std::string toString(const QString &s);

typedef unsigned char uint8;
typedef unsigned int uint;

inline float SQR(const float a) { return a*a; }

void WriteTGA(
	      const char *aFilename,
	      const int WIDTH,
	      const int HEIGHT,
	      float *data
	      );



// point used for pixel coords
struct Point2 {
  int x, y;
  Point2() {}
  Point2(const int _x, const int _y):x(_x), y(_y) {}
  friend bool operator==(const Point2 &a, const Point2 &b) {
    return a.x == b.x && a.y == b.y;
  }
};

struct Color3 {
  float r, g, b;
  Color3(){}
  Color3(const float _r, const float _g, const float _b):r(_r),g(_g),b(_b){}
  
  friend float ColorDiff(const Color3 &a, const Color3 &b) {
    return (SQR(a.r-b.r) + SQR(a.g-b.g) + SQR(a.b-b.b));
  }
  
};

template <class T>
class Image
{
 public:
  int mWidth, mHeight;
  T *mPixels;
  Image<T>(const int width, const int height):
    mWidth(width), mHeight(height) {
    mPixels = new T[width*height];
  }

  void Resize(const int width, const int height) {
    mWidth = width;
    mHeight= height;
    if (mPixels)
      delete mPixels;
    mPixels = new T[width*height];
  }
  
  
  Image<T>():mWidth(0), mHeight(0), mPixels(NULL) {}
  ~Image<T>() {
    if (mPixels)
      delete mPixels;
  }

  void Clear() {
    memset(mPixels, 0, mWidth*mHeight*sizeof(T));
  }
  
  void PutPixel(const int x, const int y, const T value) {
    mPixels[x+y*mWidth] = value;
  }

    void OrPixel(const int x, const int y, const T value) {
      mPixels[x+y*mWidth] |= value;
  }

  T GetPixel(const int x, const int y) const {
    return mPixels[x+y*mWidth];
  }

  void Export(const std::string filename) {
    WriteTGA(filename.c_str(), mWidth, mHeight, (float*) &mPixels[0]);
  }
};

inline float Random() {
  return rand() / (float)RAND_MAX;
}

extern std::ofstream Debug;

inline char *
GetPath(const char *s)
{
  int i=strlen(s);
  for (; i>0; i--) {
    if (s[i]=='/' || s[i]=='\\')
      break;
  }
  
  char *path = new char[i+1];
  int j = 0;
  for (; j<i; j++)
    path[j] = s[j];
  path[j] = 0;
  return path;
}

#endif
