// (c) MIT 2003.  All rights reserved.

package rec.fsm;

import java.util.*;
import java.awt.*;
import rec.util.*;
import rec.geo.*;
import rec.sys.*;
import rec.core.*;

public class LooseCircleRecognizer extends Recognizer
{
  public static boolean isCircle( rec.sys.Squiggle st )
  {
    int num = st.getNumberOfPoints();
    
    double dist = 0.0;
    int cntr = 0;
    int jump = num / 20;
    if( jump == 0 ) jump = 1;
    num -= jump;
    for( int i = 0; i < num; i++ ) {
      dist += Geometry.distance( st.getPointAt( cntr ), 
				 st.getPointAt( cntr + jump ) );
    }
    
    if( !( Geometry.distance( st.getFirstPoint(),
			      st.getLastPoint() )
	   //   < Math.min( st.getLength() / 50, 50.0 ) ) )
	   < dist / 5) )
      return( false );

    if( st.getLength() < 50 )
      return false;

    return( true );
  }

  //////////////////////////////////////////////////////////////////////////////

  public LooseCircleRecognizer()
  {
  }

  //////////////////////////////////////////////////////////////////////////////

  public boolean recognize( Surface s, Widget w )
  {
    rec.sys.Squiggle st = (rec.sys.Squiggle)w;

    if( st.getLength() < 40 )
      return( false );
    
    if( isCircle( st ) ) {

      Console.writeln( "circle online" );

      WCircle c = new WCircle( st.getBounds() );
      s.replaceWidget( st, c );

      return( true );
    }

    return( false );
  }

  public Iterator getInputTypes()
  {
    Vector v = new Vector();

    v.addElement( "rec.sys.Squiggle" );

    return( v.iterator() );
  }

  public Iterator getOutputTypes()
  {
    Vector v = new Vector();

    v.addElement( "rec.core.WCircle" );

    return( v.iterator() );
  }
}

////////////////////////////////////////////////////////////////////////////////
