#include "polygon_generator.hpp"

//------------------------
// PolygonGenerator::next
//------------------------

bool
PolygonGenerator::next(){
  size_t nd=0;
  while(not s.empty()){
    Step step=s.top();
    s.pop();
    poly.apply(step);
    if(poly.is_closed()) return true;
    size_t h=poly.head;
    int64 xh=h%Polygon::grid_width;
    int64 yh=h/Polygon::grid_width;
    ++nd;
    if(abs(xh-Polygon::xinit)+abs(yh-Polygon::yinit)+step.t<=max_len+1){
      size_t l=Polygon::left(h);
      size_t r=Polygon::right(h);
      size_t d=Polygon::down(h);
      size_t u=Polygon::up(h);
      size_t nt=step.t+1;
      if(poly.test(nt,l,&step)) s.emplace(&step,l,++n);
      if(poly.test(nt,r,&step)) s.emplace(&step,r,++n);
      if(poly.test(nt,d,&step)) s.emplace(&step,d,++n);
      if(poly.test(nt,u,&step)) s.emplace(&step,u,++n);
    }
  }
  return false;
}
