#ifndef _CIRCULAR_MOTION_
#define _CIRCULAR_MOTION_

#include "ofMain.h"
#include "ofAddon.h"

#define RADIAL_STEPS 20

class circularMotionDetector{
	
	public:

		circularMotionDetector(){
			for(int i = 0; i < 360; i++){
				memset(bins[i], 0, 20 * sizeof(float));
			}
		}
		
		void init(int w, int h){
			W = w;
			H = h;
		}
		
		/*	
			This code works like this
			Arm bellow sweeps radially around the image
			The 'buckets' read the pixels and create an average 
			For each radial position (degree)
			
			Then we compare the current average to the previous 
			Average and if it is greater than we have clockwise
			Motion and if it is less it is counter clockwise
			
			For each clockwise motion we incr a counter and for
			each counter clockwise motion we decr 
			
			The value of the counter at the end is the sum of all
			The different motions
			
						[ ]			
						|		\  moves in a circle
						[ ]		 \
						|		  \|
						[ ]
						|
						[ ]
						|
						|_______________	
		
		*/
		
		//should it be float?
		//more accurate?
		float process(unsigned char * motionImage, int radiusLength){
			
			int hw = (int)(float)W/2;
			int hh = (int)(float)H/2;
		
			//don't want to sweep out the image	
			if(radiusLength >= hh) radiusLength = hh-1;
		
			//pre calc the radial step size
			float tRad  =  ((float)radiusLength) / RADIAL_STEPS;	
			float iF 	= 0.0;	//our floating point version of i
			float i360  = 1.0/360; //lets get the value once
		
			int c = 0;
			int p = -1;
		
			int dir = 0;
		
			for(int i = 0; i < 360; i++, iF += 1)
			{		
				float 	avg = 0.0;
				int 	cnt = 0;
		
				for(int r = 0; r < RADIAL_STEPS; r++)
				{
					float angle = PI * 2.0 * (iF * i360);
					
					float x = sin(angle) * (r+1) * tRad;
					float y = cos(angle) * (r+1) * tRad;
					
					int ix 	= hw + (int)x;
					int iy 	= hh + (int)y;
					
					int val = motionImage[ (iy * W) + ix ];
					bins[i][r] = val;
					
					if(i != 0){
					
						//compare with the same step from 
						//the previous degree
						int compareVal = bins[i-1][r];  
					
						if(val != 0 && compareVal != 0){
							if(val > compareVal)dir++;			
							else if(val < compareVal) dir--;
						}
					}	
					
					//need to compare this degree against degree 0
					if(i == 359){
						int compareVal = bins[i][r];  
						val = bins[0][r];  
					
						if(val != 0 && compareVal != 0){
							if(val > compareVal)dir++;			
							else if(val < compareVal) dir--;
						}
					}					
				}
			}
			
			//the only factors that effect the scale of dir
			//are RADIAL_STEPS 
			
			float value = (float)dir / RADIAL_STEPS;
			return value;
		}


	//our vars
	float bins[360][RADIAL_STEPS];
	int W, H;	
};

#endif