/* A program to drive a couple of stepper motors */
/* Spirograph meets Etch A Sketch */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "libesketch.h"


/* Good Patterns:
 *  a    b    c   e   description
 * ---  ---  --- --- -------------
 * 150,  40,  90  5   23 petals
 */

int main( int argc, char **argv )
{
    float x, y;
    float d;		/* Angular position of moving circle */

    int a = 170;	/* Radius of center of moving circle */
    int b =  40;	/* Radius of moving circle */
    int c =  90;	/* Pen position along moving circle radius */

    int e = 1;		/* Iterations */
    int i;		/* Variable */

    int xc = 500;	/* Screen center X coordinate */
    int yc = 350;	/* Screen center Y coordinate */

    int min_a_b;	/* Minimum of a and b */
    int symmetry;	/* Number of petals */


    printf( "Usage: spiro outer_radius inner_radius offset_radius\n" );
    if( argc == 4 )
    {
	a = atoi( argv[ 1 ] );
	b = atoi( argv[ 2 ] );
	c = atoi( argv[ 3 ] );
    }

    /* Calculate the minimum of a and b */
    min_a_b = ( a < b ) ? a : b;

    /* Calculate number of interations for the full pattern */

    for( i = 2; i <= b; i++ )
    {
	if( ( a + b ) % i == 0 && b % i == 0 ) e = i;
    }

    /* Calculate symmetry */
    symmetry = ( a + b + b ) / e;

    e = b / e;

    /* Print parameters */
    printf( "Outer Circle radius = %d\n", a );
    printf( "Inner Circle radius = %d\n", b );
    printf( "Offset Circle radius = %d\n", c );
    printf( "Iterations = %d\n", e );
    printf( "Symmetry = %d\n", symmetry );

    /* Direct hw access */
    init();

    /* Reset to start point */
    reset( a + c + xc, yc );

    /* Draw a spirograph */
    for( d = 0; d < e * 2 * M_PI; d += 0.01 )
    {
	/* Calculate x and y */
	x = a * cos( d ) + c * cos( (float)a / b * d + d );
	y = a * sin( d ) - c * sin( (float)a / b * d + d );

        drawto( x + xc, y + yc );
    }

    /* Turn off motor drivers */
    stop();

    return 0;
}
