
#include "cornerFinder.h"
	
cornerFinder::cornerFinder(){
}

int cornerFinder::findCorners(vector <ofxVec2f> & vecList, int sensitivity){
			
	int length = vecList.size();	
	if( dist.size() != length){
		
		dist.clear();	
		highest.clear();
		tipList.clear();
		
		dist.assign(length, bool());
		highest.assign(length, float());
		tipList.assign(length, int());
	}
				
	//do it here
	//think about resampling
	//chain code vs vector code.
	//maybe not true or false but a rating?			
	//average angle

	int storeCount 	= 0;
	float fortyFive = (30.0  * PI) / 180.0;
	ofxVec2f dist1;
	ofxVec2f dist2;

	float angle = 0;
	
	for(int i = 0; i < length; i++){
	
		int nextPoint = i+10;
		if(nextPoint >= length )nextPoint -= length;
	
		int prevPoint = i-10;
		if(prevPoint < 0 )prevPoint += length;
	
		dist1 = vecList[nextPoint] - vecList[i];				
		dist2 = vecList[i] - vecList[prevPoint];				
		
		float angle1 = atan2f(dist1.y, dist1.x);
		float angle2 = atan2f(dist2.y, dist2.x);
		
		float ang 	 = fabs(angle1 - angle2);
		
		if( ang > PI ){
			ang = (2.0 * PI) - ang;
		}
		
		if( ang > fortyFive){
			dist[i] = ang;
		}else{
			dist[i]=-1;
		}
		
		highest[i] = false;

	}		
	
	
	int count = 0;
	
	for(int i = 0; i < length; i++){
		
		float  val =  dist[i];
		if(val <= 0) continue;
		
		bool found = true;
		for(int j = 1; j < sensitivity; j++){
			int n = i + j;
			if(n >= length) n -= length;
			
			int p = i - j;
			if(p < 0) p += length;
			
			if( val < dist[p] || val < dist[n] ){
				found = false;
			}
		}
		highest[i] = found;
		
		if(found){
			tipList[count] = i;
			count++;
		}
	}
	
	
	len = length;
	return count;		
}
		
//-----------------------------
int cornerFinder::getTipIndex(int whichTip){
	if(whichTip < 4){
		return tipList[whichTip];
	}
	else return -1;
}
	