#include <iostream>
#include <cstdlib>
#include "PostScript.hpp"

using namespace std;

class Spiro : public PostScript {
	private:
		int ring;
		int disc;
		int hole;
		int desv;
		int reso;

		void spiro(double& x, double& y, double a, double d);		
		int  mcm(int a, int b);		
	public:
		Spiro(const char* nombre);
		void SetRing(int r) { ring= r; };
		void SetDisc(int d) { disc= d; };
		void SetHole(int h) { hole= h; };
		void SetDesv(int v) { desv= v; };
		void SetReso(int s) { reso= s; };
		void Ejecutar(void);

};

int Spiro::mcm(int a, int b)
{
	if (a<0) 
		a= -a;
	if (b<0) 
		b= -b;
	int ma= a;
	int mb= b;
	while (ma!=mb) { 
		if (ma<mb) 
			ma+= a;
		else
			mb+= b;
	}
	return ma;
}


Spiro::Spiro(const char* nombre) : PostScript(nombre)
{
	ring= 100;
	disc= 40;
	hole= 40;
	desv= 0;
	reso= 64;
	*this << "1 10 div dup scale\n";
	*this << "0.1 setlinewidth\n";
}

void Spiro::spiro(double& x, double& y, double alfa, double dv)
{
	double a= alfa * M_PI / 180.0;
	double d= dv * M_PI / 180.0;
	double t= double(ring-disc) / double(disc);
	x= (ring-disc)*cos(a+d) + hole*cos(t*a);
	y= (ring-disc)*sin(a+d) - hole*sin(t*a);
}

void Spiro::Ejecutar(void)
{
	double x, y;
	int m= mcm(ring, disc);
	int ciclos= m/ring;
	double h= 360.0 / reso;
	double ang= 0.0;
	spiro(x, y, ang, desv);
	MoveTo(x,y);
	for (int c=0; c<ciclos; ++c) {
		for (int p=0; p<reso; ++p) {
			ang+= h;
			spiro(x, y, ang, desv);
			LineTo(x,y);
		}
	}
}


int main(int argc, char* argv[])
{
	Spiro s("spiro.ps");
	for (int p= 1; p<argc; ++p) {
		switch ( argv[p][0] ) {
			case 'r':
			case 'R': 	s.SetRing( atoi(argv[++p]) );
						break;
			case 'd':
			case 'D': 	s.SetDisc( atoi(argv[++p]) );
						break;
			case 'h':
			case 'H': 	s.SetHole( atoi(argv[++p]) );
						break;
			case 'v':
			case 'V': 	s.SetDesv( atoi(argv[++p]) );
						break;
			case 's':
			case 'S': 	s.SetReso( atoi(argv[++p]) );
						break;
			case 'e':
			case 'E':	s.Ejecutar();
						break;
			case 'c':
			case 'C':	{
							double r= atof(argv[++p]) / 255;
							double g= atof(argv[++p]) / 255;
							double b= atof(argv[++p]) / 255;
							s.SetColor(r, g, b);
							break;
						}
			case 'q':
			case 'Q':	p= argc;
						break;
		}
	}

	return EXIT_SUCCESS;
}
