

// Save the current preferences
var startRulerUnits = app.preferences.rulerUnits
var startTypeUnits = app.preferences.typeUnits
var startDisplayDialogs = app.displayDialogs
// Set Adobe Photoshop CS5 to use pixels and display no dialogs
app.preferences.rulerUnits = Units.PIXELS
app.preferences.typeUnits = TypeUnits.PIXELS
app.displayDialogs = DialogModes.NO

var lastV=100;
var lastH=100;

//Pastes the Background of the montage in
open(File(directory1))

// use the document name for the layer name in the merged document
var docName = app.activeDocument.name
// flatten the document so we get everything and then copy
app.activeDocument.flatten()
app.activeDocument.selection.selectAll()
app.activeDocument.selection.copy()
lastH=app.activeDocument.width.value;
lastV=app.activeDocument.height.value;
// don’t save anything we did
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES)

try{app.activeDocument.activeLayer= pasteImageLayer;} catch(err){};
var baseLayer=app.activeDocument.activeLayer;


if (app.activeDocument.width< h + lastH ) {
    app.activeDocument.resizeCanvas(h + lastH, app.activeDocument.height, AnchorPosition.TOPLEFT)
    }
if (app.activeDocument.height< v + lastV ) {
    app.activeDocument.resizeCanvas(app.activeDocument.width, v + lastV, AnchorPosition.TOPLEFT)
    }

var selRegion = Array(
Array(h, v),
Array(h + lastH, v),
Array(h + lastH, v + lastV),
Array(h, v + lastV),
Array(h, v))
app.activeDocument.selection.select(selRegion)
app.activeDocument.paste()

// change the layer name and opacity
app.activeDocument.activeLayer.name = layerName
if (linkTo) app.activeDocument.activeLayer.link(baseLayer)

// Reset the application preferences
app.preferences.rulerUnits = startRulerUnits
app.preferences.typeUnits = startTypeUnits
app.displayDialogs = startDisplayDialogs

