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

package rec.fun;

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

public class PolygonDuster extends Recognizer {

  public boolean recognize( Surface s, Widget w )
  {
    GPolygon gp = ((WPolygon)w).getPolygon();

    GPoint[] ps = gp.getPoints();
    GPoint[] nps = new GPoint[ ps.length ];
    boolean new_one = false;
    int cur, nxt;
    double d, del;

    cur = ps.length - 1;
    for ( int i = 0; i < ps.length; i++ )
      {
	nxt = i;

	d = Geometry.distance( ps[cur], ps[nxt] );
	d /= 20;
	
	del = Math.abs(ps[cur].x-ps[nxt].x);
	if ( (del > 0) && ( del < d ) )
	  {
	    nps[cur] = new GPoint( (ps[cur].x + ps[nxt].x) / 2,
				   ps[cur].y );

	    new_one = true;
	  }
	del = Math.abs(ps[cur].y-ps[nxt].y);

	if ( (del > 0) && ( del < d ) )
	  {
	    nps[cur] = new GPoint( (ps[cur].y + ps[nxt].y) / 2,
				   ps[cur].y );

	    new_one = true;
	  }
	
	else
	  nps[cur] = ps[cur];
	
	cur = nxt;
      }


    if ( new_one )
      {
	WPolygon npl = new WPolygon( nps );

	s.replaceWidget( w, npl );

	return true;
      }

    return false;
  }


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

    v.addElement( "rec.core.widgets.WPolygon" );

    return( v.iterator() );
  }

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

    v.addElement( "rec.core.widgets.WPolygon" );

    return( v.iterator() );
  }

}
