//creates ellipse with random orientation

macro "Random Ellipse Tool - Ca0cT0e12eT8e12l" {
  editEllipse();
}

function  editEllipse() {
  setTool(0);//avoid consumption of button-down event
  leftButton=16;
  x2 = 0;
  y2 = 0;
  limit1 = 0.25;//vary aspect = 0..1 within distance =(limit1..limit2) * major
  limit2 = 1.33;
  getCursorLoc(xMajor1, yMajor1, z, flags);
  kk = 1;
  for (loop = 1; loop<=2; loop++){
    do { wait(5);
      getCursorLoc(x3, y3, z, flags);
      if (x2 != x3 || y2 != y3){
        x2 = x3;
        y2 = y3;
        if (loop == 1){
          xMajor2 = x3;
          yMajor2 = y3;
          dxa = (x3-xMajor1);
          dya = (y3-yMajor1);
          elMajor = sqrt(dxa * dxa + dya * dya);
          makeEllipse2(xMajor1, yMajor1, xMajor2, yMajor2, 1/limit2);
        }
        if (loop == 2){
          dxb = (x3-xMajor1);
          dyb = (y3-yMajor1);
          rad2 = sqrt(dxb * dxb + dyb * dyb);
          
          aspect = (rad2 - elMajor*limit1)/elMajor/limit2/(1-limit1);
          if (aspect < 0) aspect = 0;
          if (aspect > 1) aspect = 1;
          phiB = atan2(dyb, dxb);
          xMajor2 = xMajor1 + cos(phiB) * elMajor;
          yMajor2 = yMajor1 + sin(phiB) * elMajor;
          makeEllipse2(xMajor1, yMajor1, xMajor2, yMajor2, aspect);
        }
      }
    done = ( (loop==1 && flags&leftButton == 0) || (loop ==2 && flags&leftButton != 0));}
    while (!done);//while mouse is down
  }
  do{
    getCursorLoc(x3, y3, z, flags);
    wait(20);
  }while( flags&leftButton != 0)  ;
  makeEllipse2(xMajor1, yMajor1, xMajor2, yMajor2, aspect); 
}


function  makeEllipse2(p1x, p1y, p2x, p2y, aspect){
  k36 = 36;
  elxx = newArray(k36);
  elyy = newArray(k36);
  elCenterX = (p1x + p2x)/2;
  elCenterY = (p1y + p2y)/2;
  
  dx = p2x - p1x;
  dy = p2y - p1y;
  elMajor = sqrt(dx * dx + dy * dy);
  elMinor = elMajor * aspect;
  phiB = atan2(dy, dx);         
  elAlpha = phiB * 180/PI;
          
  for (jj = 0; jj < k36; jj++){
    degrees = jj * 360/k36;
    beta1 = degrees/180*PI;
    dx = cos(beta1) * elMajor/2;
    dy = sin(beta1)  * elMinor/2;
    beta2 = atan2(dy, dx);
    rad = sqrt(dx * dx + dy * dy);
    beta3 = beta2+ elAlpha/180 * PI;
    dx2 = cos(beta3) * rad;
    dy2 = sin(beta3) * rad;
    elxx[jj] = elCenterX + dx2;
    elyy[jj] = elCenterY + dy2;
  }
  makeSelection("freehand", elxx, elyy);
}