#include "ifs.hpp"
#include <vector>
#include <cstdarg>
#include <cstdlib>
#include "point.hpp"
#include "mathfunction.hpp"

TIFS::TIFS()
{
 EnabledIFSs = 0;
}

TIFS::~TIFS()
{
 //! Loop through and make sure all TMathFunctions are deleted (as they use up lots of memory)!
}

void TIFS::Add(const char *sx, const char *sy, float p)
{
 TMathFunctionInfo info;

 info.Enabled = 1;
 info.fx = new TMathFunction(sx);
 info.fy = new TMathFunction(sy);
 info.RawInput.Type = 2;
 info.RawInput.sx = sx;
 info.RawInput.sy = sy;
 info.p = p;

 v.push_back(info);

 EnabledIFSs++;

 return;
}

//FIXME
void TIFS::Add(TAffineTransformation t, float p)
{
 TMathFunctionInfo info;

 info.Enabled = 1;
 info.fx = new TMathFunction("x");
 info.fy = new TMathFunction("y");
 info.RawInput.Type = 1;
 info.RawInput.t = t;
 info.p = p;
 v.push_back(info);

 EnabledIFSs++;

 return;
}

void TIFS::Delete(int i)
{
 register unsigned int j;

 for (j = i+1; j < v.size(); j++)
 {
  v[j-1] = v[j];
 }

 v.pop_back();

 return;
}

TPoint TIFS::operator()(TPoint p)
{
 int i;
 float j;
 register unsigned int k;
 TPoint temp;
 if (v[1].p == 0)
 {
  i = rand() % v.size();
  temp.x = (*(v[i].fx))(p.x, p.y);
  temp.y = (*(v[i].fy))(p.x, p.y);
 }
 else
 {
  i = rand() % 100;
  j = 0;
  for (k = 0; k < v.size(); k++)
  {
   if ((j <= i) && (i < j + v[k].p))
   {
    temp.x = (*(v[k].fx))(p.x, p.y);
    temp.y = (*(v[k].fy))(p.x, p.y);
   }
   j += v[k].p;
  }
 }

 return temp;
}

/*
 **************************************************************
                                                              */

TReadOnlyIFS::TReadOnlyIFS(TIFS *xIFSPtr)
{
 IFSPtr = xIFSPtr;
}

TReadOnlyIFS::~TReadOnlyIFS()
{
}

TPoint TReadOnlyIFS::operator()(TPoint p)
{
 return (*IFSPtr)(p);
}
