// Reorder montages created with
// Image>Stacks>Make Montage
// (or create puzzles) with this macro
// set adapted from arrowtool.txt
// Author Jerome Mutterer

  var mw = 2;
  var mh = 3;
  var iw, ih, t;

  macro "Unused Tool-1 - " {}  // leave slot between text tool and magnifying glass unused
  macro "Unused Tool-2 - " {}  // leave slot between dropper and shuffler unused

  macro "Montage Shuffler Tool - C000D37D38D39D46D47D4bD4cD55D56D57D5aD5bD5cD5dD62D65D66D69D6aD6bD6cD6dD6eD72D73D74D75D79D7aD7bD7cD7dD7eD82D83D84D85D86D87D8bD8cD8dD8eD92D93D94D95D96D9aD9bD9cDa3Da4Da5DaaDabDb3Db4Db5Db9DbaDbbDc8Dc9DcaDd8Dd9"{
      getCursorLoc(x, y, z, flags); 
      xstart = x; ystart = y; 
      x2=x; y2=y; 
      while (flags&16 !=0) { 
          getCursorLoc(x, y, z, flags); 
          if (x!=x2 || y!=y2) 
              makeLine(xstart, ystart, x, y); 
              x2=x; y2=y; 
              wait(10); 
      }
      if (x!=xstart || y!=ystart) {
              sc = floor(xstart/(iw/mw));
		tc = floor(x/(iw/mw));
		sr = floor(ystart/(ih/mh));
		tr = floor(y/(ih/mh));
		swap(sc,sr,tc,tr);
      }
  }

  macro "Montage Shuffler Tool Options..." {
      Dialog.create("Shuffler");
      Dialog.addNumber ("Width:", mw);
      Dialog.addNumber ("Height:", mh);
      Dialog.show();
      mw = Dialog.getNumber();
      mh = Dialog.getNumber();
      iw = getWidth();
      ih = getHeight();
      t = getTitle();
  }

  function swap (a,b,c,d) {
      setupUndo();
      setBatchMode(true);
      makeRectangle(a*(iw/mw),b*(ih/mh),(iw/mw),(ih/mh));
      run("Duplicate...", "title=tmp");
      selectWindow(t);
      makeRectangle(c*(iw/mw),d*(ih/mh),(iw/mw),(ih/mh));
      run("Copy");
      makeRectangle(a*(iw/mw),b*(ih/mh),(iw/mw),(ih/mh));
      run("Paste");
      selectWindow("tmp");
      run("Select All");
      run("Copy");
      selectWindow(t);
      makeRectangle(c*(iw/mw),d*(ih/mh),(iw/mw),(ih/mh));
      run("Paste");
      setBatchMode(false);
  }

  // bonus Lena puzzle game

  macro "Lena Puzzle Tool -  " {
  }

  macro "Lena Puzzle Tool Selected"{
      run("Lena (68K)");
      t = getTitle();
      iw = getWidth();
      ih = getHeight();
      mw = 4;
      mh = 4;
      for (i=0; i<20; i++) {
          c1 = floor (random()*5);
          r1 = floor (random()*5);
          c2 = floor (random()*5);
          r2 = floor (random()*5);
          swap(c1,r1,c2,r2);
      }
      setTool(16);
      exit("Move pieces by dragging\nwith the shuffler tool");
  }
