#include "polarline.h"
#include <iomanip>

namespace seemicro
{

std::ostream& operator<<(std::ostream& s, const polarLine& l)
{
  return s << "r=" << std::setprecision(2) << std::fixed << l.r
    << " theta=" << l.theta/M_PI*180 << "° ("
    << l.theta << ")";
}

void polarLine::draw(IplImage *img, double color)
{
  int w = img->width;
  int h = img->height;

  // normalisieren
  if(r<0)
  {
    r=fabs(r);
    theta += M_PI;
  }

  CvPoint p1 = cvPoint(0, 0);
  CvPoint p2 = cvPoint(w, h);
  if(fabs(sin(theta))>1e-6)
  {
    p1.y = -int((r+w/2*cos(theta))/sin(theta));
    p2.y = -int((r-w/2*cos(theta))/sin(theta));
    p1.y += h/2;
    p2.y += h/2;
  }
  else
  {
    // senkrechte linie
    // 2 fälle: theta == 0 und theta == M_PI
    // da theta periodisch ist, gibt es sogar noch mehr fälle...
    if(fabs(theta)<0.1)
    {
      p1.x=int(w/2+r);
      p2.x=int(w/2+r);
    }
    else
    {
      p1.x=int(w/2-r);
      p2.x=int(w/2-r);
    }
  }

  polarLine back;
  back.fromCart(img->width, img->height, p1, p2);
#if defined(DEBUG) || defined (_DEBUG)
  std::cerr << "this: " << *this << " back: " << back << std::endl;
#endif

  cvLine(img, p1, p2, color);
}

} // namespace

