// This macro measures the angle and length of a line selection.
// Save this file to the plugins folder and restart 
// ImageJ to create a "Measure Angle And Length" command.
// Use the Plugins>Shortcuts>Create Shortcut command 
// to create a keyboard shortcut.
//
// Or define a shortcut key and add this macro to the 
// StartupMacros file. For example, to use the "1" key
// as the shortcut, change the first line from
//     macro "Measure Line" {
// to
//    macro "Measure Line [1]" {

  macro "Measure Line" {
      if (selectionType!=5)
          exit("Straight line selection required");
      getLine(x1, y1, x2, y2, lineWidth);
      getPixelSize(unit, width, height, depth);
      x1*=width; y1*=height; x2*=width; y2*=height; 
      angle = getAngle(x1, y1, x2, y2);
      length = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
      row = nResults();
      setResult("Angle", row, angle);
      setResult("Length", row, length);
      updateResults();
  }


  // Returns the angle in degrees between the specified line and the horizontal axis.
  function getAngle(x1, y1, x2, y2) {
      q1=0; q2orq3=2; q4=3; //quadrant
      dx = x2-x1;
      dy = y1-y2;
      if (dx!=0)
          angle = atan(dy/dx);
      else {
          if (dy>=0)
              angle = PI/2;
          else
              angle = -PI/2;
      }
      angle = (180/PI)*angle;
      if (dx>=0 && dy>=0)
           quadrant = q1;
      else if (dx<0)
          quadrant = q2orq3;
      else
          quadrant = q4;
      if (quadrant==q2orq3)
          angle = angle+180.0;
      else if (quadrant==q4)
          angle = angle+360.0;
      return angle;
  }
