


    // +------------
    // | construct array of xy pairs suitable
    // | for a selection rectangle.
    function makeRectPath(l,t,r,b)
    {
        var result = new Array
        (
            new Array(l,t),
            new Array(l,b),
            new Array(r,b),
            new Array(r,t),
            new Array(l,t)
        );
        return result;
    }

    // +---------------------
    // | select a rectangle and copy
    // | it into the new doc. assume it fits just right.
    function copyTile(srcDoc,dstDoc,l,t,r,b)
    {
        // when selecting (or many other things) you'll get an Error Dialog
        // telling you it needs to be the Active Document if it isnt.

        // also, you can only copy merged IF there's more than one layer. So.

        var layerCount = srcDoc.artLayers.length;
        var doMerged = (layerCount > 1) ? true : false;
        var name = "(" + l + "," + t + "," + r + "," + b + ")";

        app.activeDocument = srcDoc;
        var rectPath = makeRectPath(t,l,b,r);
        if(srcDoc.activeLayer == null)
            srcDoc.activeLayer = srcDoc.artLayers[0];
        srcDoc.selection.select(rectPath);
        srcDoc.selection.copy(doMerged); // copy merged? layers

        app.activeDocument = dstDoc;
        dstDoc.selection.selectAll();
        var newLayer = dstDoc.paste(true);
        newLayer.name = name;
        return newLayer;
    }

    function makeTileFromCurrentDoc()
    {

        // +--------------
        // | Save the current preferences
        // |
        var startRulerUnits = app.preferences.rulerUnits
        var startTypeUnits = app.preferences.typeUnits
        // +--------------
        // | Set pixel units
        // |
        app.preferences.rulerUnits = Units.PIXELS
        app.preferences.typeUnits = TypeUnits.PIXELS
       
        var d = app.activeDocument;
        var docName = d.name;
        var w = d.width.value;
        var h = d.height.value;

        // +---------
        // | compute our fold-lines
        var w13 = w * 1.0 / 3.0;
        var w23 = w * 2.0 / 3.0;
        var h13 = h * 1.0 / 3.0;
        var h23 = h * 2.0 / 3.0;

        // +-----------
        // | create new document to receive tile
        // |
        var tileWidth = w23 - w13;
        var tileHeight = h23 - h13;
        var tileDoc = app.documents.add(tileWidth,tileHeight,72,docName + "_tile",NewDocumentMode.RGB);

        // +-------------------
        // | copy each of 9 cells to new tile
        // |
        copyTile(d,tileDoc,0,0,w13,h13);
        copyTile(d,tileDoc,w13,0,w23,h13);
        copyTile(d,tileDoc,w23,0,w,h13);

        copyTile(d,tileDoc,0,h23,w13,h);
        copyTile(d,tileDoc,w13,h23,w23,h);
        copyTile(d,tileDoc,w23,h23,w,h);

        copyTile(d,tileDoc,0,h13,w13,h23);
        copyTile(d,tileDoc,w23,h13,w,h23);

        copyTile(d,tileDoc,w13,h13,w23,h23);

        return;
    }

makeTileFromCurrentDoc();

// the end
