#target photoshop

// CAHDD Watermark Manager
// Version: 1.1
// CAHDD.org
//
// This script applies CAHDD stage watermarks or custom watermark graphics
// to a current Photoshop document or a batch folder of images.
// Original source files are left untouched.

(function () {

    var originalUnits = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;

    var PREF_FOLDER = Folder.myDocuments + "/CAHDD";
    var PREF_FILE = PREF_FOLDER + "/CAHDD_Watermark_Manager_Prefs.txt";

    var DEFAULTS = {
        watermarkFolder: "",
        sourceFolder: "",
        outputFolder: "",
        stage: "CAHDD4.png",
        watermarkMode: "CAHDD Stage Watermark",
        customWatermark: "",
        position: "Bottom Right",
        sizePercent: "4",
        opacity: "30",
        padding: "40",
        mode: "Current Open Image",
        format: "JPG",
        quality: "10",
        suffix: "_CAHDD",
        useDefaultOutput: "false",
        leaveCurrentCopyOpen: "true",
        openBatchSamples: "true",
        batchSampleCount: "6"
    };

    function ensurePrefFolder() {
        var f = new Folder(PREF_FOLDER);
        if (!f.exists) f.create();
    }

    function loadPrefs() {
        var p = {};
        for (var k in DEFAULTS) p[k] = DEFAULTS[k];

        var f = new File(PREF_FILE);
        if (f.exists) {
            f.open("r");
            while (!f.eof) {
                var line = f.readln();
                var parts = line.split("=");
                if (parts.length >= 2) p[parts[0]] = parts.slice(1).join("=");
            }
            f.close();
        }
        return p;
    }

    function savePrefs(p) {
        ensurePrefFolder();
        var f = new File(PREF_FILE);
        f.open("w");
        for (var k in p) f.writeln(k + "=" + p[k]);
        f.close();
    }

    function dropdownSelect(dd, value) {
        for (var i = 0; i < dd.items.length; i++) {
            if (dd.items[i].text === value) {
                dd.selection = i;
                return;
            }
        }
        if (dd.items.length > 0) dd.selection = 0;
    }

    function validNumber(value, fallback, min, max) {
        var n = parseFloat(value);
        if (isNaN(n)) n = fallback;
        if (n < min) n = min;
        if (n > max) n = max;
        return n;
    }

    function stripExtension(name) {
        return name.replace(/\.[^\.]+$/, "");
    }

    function placeFile(file) {
        var desc = new ActionDescriptor();
        desc.putPath(charIDToTypeID("null"), file);
        desc.putEnumerated(charIDToTypeID("FTcs"), charIDToTypeID("QCSt"), charIDToTypeID("Qcsa"));
        executeAction(charIDToTypeID("Plc "), desc, DialogModes.NO);
    }

    function getLayerBoundsPx(layer) {
        var b = layer.bounds;
        return {
            left: b[0].as("px"),
            top: b[1].as("px"),
            right: b[2].as("px"),
            bottom: b[3].as("px"),
            width: b[2].as("px") - b[0].as("px"),
            height: b[3].as("px") - b[1].as("px")
        };
    }

    function positionLayer(layer, position, padding) {
        var doc = app.activeDocument;
        var docW = doc.width.as("px");
        var docH = doc.height.as("px");
        var b = getLayerBoundsPx(layer);
        var x, y;

        if (position === "Bottom Right") {
            x = docW - b.width - padding;
            y = docH - b.height - padding;
        } else if (position === "Bottom Left") {
            x = padding;
            y = docH - b.height - padding;
        } else if (position === "Top Right") {
            x = docW - b.width - padding;
            y = padding;
        } else if (position === "Top Left") {
            x = padding;
            y = padding;
        } else {
            x = (docW - b.width) / 2;
            y = (docH - b.height) / 2;
        }

        layer.translate(x - b.left, y - b.top);
    }

    function applyWatermarkToDocument(watermarkFile, watermarkLabel, sizePercent, opacity, padding, position) {
        var doc = app.activeDocument;
        placeFile(watermarkFile);

        var layer = doc.activeLayer;
        layer.name = "CAHDD Watermark - " + stripExtension(watermarkLabel);

        var docW = doc.width.as("px");
        var b = getLayerBoundsPx(layer);
        var targetW = docW * (sizePercent / 100);
        var scale = (targetW / b.width) * 100;

        layer.resize(scale, scale, AnchorPosition.MIDDLECENTER);
        positionLayer(layer, position, padding);
        layer.opacity = opacity;
    }

    function getImageFiles(folder) {
        return folder.getFiles(function (f) {
            if (!(f instanceof File)) return false;
            return /\.(jpg|jpeg|png|tif|tiff|psd)$/i.test(f.name);
        });
    }

    function getWatermarkFiles(folder) {
        return folder.getFiles(function (f) {
            if (!(f instanceof File)) return false;
            return /\.(png|jpg|jpeg|tif|tiff|psd)$/i.test(f.name);
        });
    }

    function ensureOutputFolder(path) {
        var f = new Folder(path);
        if (!f.exists) f.create();
        return f;
    }

    function getOutputFile(originalFile, outputFolder, suffix, format) {
        var baseName = stripExtension(originalFile.name);
        var saveFolder = outputFolder && outputFolder.exists ? outputFolder : originalFile.parent;
        var ext = format === "PSD" ? ".psd" : format === "PNG" ? ".png" : ".jpg";
        return new File(saveFolder.fsName + "/" + baseName + suffix + ext);
    }

    function saveCopy(doc, outputFolder, originalFile, suffix, format, quality) {
        var outFile = getOutputFile(originalFile, outputFolder, suffix, format);

        if (format === "PSD") {
            var psdOpts = new PhotoshopSaveOptions();
            psdOpts.layers = true;
            psdOpts.embedColorProfile = true;
            doc.saveAs(outFile, psdOpts, true, Extension.LOWERCASE);

        } else if (format === "PNG") {
            var pngOpts = new PNGSaveOptions();
            doc.saveAs(outFile, pngOpts, true, Extension.LOWERCASE);

        } else {
            var jpgOpts = new JPEGSaveOptions();
            jpgOpts.quality = quality;
            jpgOpts.embedColorProfile = true;
            jpgOpts.formatOptions = FormatOptions.STANDARDBASELINE;
            jpgOpts.matte = MatteType.NONE;
            doc.saveAs(outFile, jpgOpts, true, Extension.LOWERCASE);
        }

        return outFile;
    }

    function getCurrentDocumentFileOrNull(doc) {
        try {
            if (doc.fullName && doc.fullName.exists) return doc.fullName;
        } catch (e) {}
        return null;
    }

    function saveCurrentOpenImageCopy(watermarkFile, watermarkLabel, sizePercent, opacity, padding, position, outputFolder, suffix, format, quality, leaveOpen) {
        if (!app.documents.length) {
            alert("Open an image first, or choose Batch Folder mode.");
            return false;
        }

        var originalDoc = app.activeDocument;
        var originalFile = getCurrentDocumentFileOrNull(originalDoc);

        if (!originalFile && (!outputFolder || !outputFolder.exists)) {
            alert("This open document has not been saved yet.\n\nChoose an output folder first so the watermarked copy has somewhere to save.");
            return false;
        }

        var nameSourceFile = originalFile;
        if (!nameSourceFile) {
            nameSourceFile = new File(outputFolder.fsName + "/" + originalDoc.name);
        }

        var duplicateName = stripExtension(originalDoc.name) + "_CAHDD_PREVIEW";
        var dup = originalDoc.duplicate(duplicateName, false);
        app.activeDocument = dup;

        applyWatermarkToDocument(watermarkFile, watermarkLabel, sizePercent, opacity, padding, position);
        saveCopy(dup, outputFolder, nameSourceFile, suffix, format, quality);

        if (leaveOpen) {
            app.activeDocument = dup;
        } else {
            dup.close(SaveOptions.DONOTSAVECHANGES);
            app.activeDocument = originalDoc;
        }

        return true;
    }

    var prefs = loadPrefs();

    var dlg = new Window("dialog", "CAHDD Watermark Manager", undefined, { resizeable: true });
    dlg.orientation = "column";
    dlg.alignChildren = "fill";
    dlg.margins = 14;
    dlg.preferredSize = [760, 640];

    var title = dlg.add("statictext", undefined, "CAHDD Watermark Manager");
    title.graphics.font = ScriptUI.newFont("Arial", "BOLD", 16);

    dlg.add("statictext", undefined, "Visible authorship and transparency watermark workflow.");

    var tabs = dlg.add("tabbedpanel");
    tabs.alignChildren = "fill";
    tabs.preferredSize = [730, 500];

    var setupTab = tabs.add("tab", undefined, "Setup");
    setupTab.orientation = "column";
    setupTab.alignChildren = "fill";
    setupTab.margins = 12;

    var about = setupTab.add("statictext", undefined, "CAHDD means Computer Aided Human Designed & Developed. This tool helps creators mark how human direction, digital tools, and AI-assisted processes contributed to finished work.");
    about.characters = 90;

    var modePanel = setupTab.add("panel", undefined, "Processing Mode");
    modePanel.orientation = "column";
    modePanel.alignChildren = "fill";
    modePanel.margins = 10;

    var modeDropdown = modePanel.add("dropdownlist", undefined, ["Current Open Image", "Batch Folder"]);
    dropdownSelect(modeDropdown, prefs.mode);

    var wmPanel = setupTab.add("panel", undefined, "Watermark Folder");
    wmPanel.orientation = "column";
    wmPanel.alignChildren = "fill";
    wmPanel.margins = 10;

    var wmText = wmPanel.add("statictext", undefined, prefs.watermarkFolder || "No watermark folder selected");
    wmText.characters = 90;
    var wmBtn = wmPanel.add("button", undefined, "Choose Watermark Folder");

    var batchPanel = setupTab.add("panel", undefined, "Batch / Output Folders");
    batchPanel.orientation = "column";
    batchPanel.alignChildren = "fill";
    batchPanel.margins = 10;

    var srcText = batchPanel.add("statictext", undefined, prefs.sourceFolder || "No source folder selected");
    srcText.characters = 90;
    var srcBtn = batchPanel.add("button", undefined, "Choose Source Image Folder");

    var outText = batchPanel.add("statictext", undefined, prefs.outputFolder || "No output folder selected");
    outText.characters = 90;
    var outBtn = batchPanel.add("button", undefined, "Choose Output Folder");

    var useDefaultOutputCheck = batchPanel.add("checkbox", undefined, "Use default CAHDD_Output folder inside source folder");
    useDefaultOutputCheck.value = prefs.useDefaultOutput === "true";

    var clearOutBtn = batchPanel.add("button", undefined, "Clear Output Folder / Save Beside Originals");

    var optionsTab = tabs.add("tab", undefined, "Options");
    optionsTab.orientation = "column";
    optionsTab.alignChildren = "fill";
    optionsTab.margins = 12;

    var optsPanel = optionsTab.add("panel", undefined, "Watermark Options");
    optsPanel.orientation = "column";
    optsPanel.alignChildren = "fill";
    optsPanel.margins = 10;

    optsPanel.add("statictext", undefined, "Watermark Mode:");
    var watermarkModeDropdown = optsPanel.add("dropdownlist", undefined, [
        "CAHDD Stage Watermark",
        "Custom Watermark File"
    ]);
    dropdownSelect(watermarkModeDropdown, prefs.watermarkMode);

    optsPanel.add("statictext", undefined, "CAHDD Stage:");
    var stageDropdown = optsPanel.add("dropdownlist", undefined, [
        "CAHDD0.png",
        "CAHDD1.png",
        "CAHDD2.png",
        "CAHDD3.png",
        "CAHDD4.png",
        "CAHDD5.png",
        "CAHDDX.png"
    ]);
    dropdownSelect(stageDropdown, prefs.stage);

    optsPanel.add("statictext", undefined, "Custom Watermark File:");
    var customDropdown = optsPanel.add("dropdownlist", undefined, []);
    customDropdown.preferredSize.width = 300;

    function populateCustomDropdown(folderPath) {
        customDropdown.removeAll();

        var folder = new Folder(folderPath);
        if (!folder.exists) return;

        var files = getWatermarkFiles(folder);

        for (var i = 0; i < files.length; i++) {
            customDropdown.add("item", files[i].name);
        }

        if (customDropdown.items.length > 0) {
            dropdownSelect(customDropdown, prefs.customWatermark);
        }
    }

    function updateWatermarkModeUI() {
        var isCustom = watermarkModeDropdown.selection && watermarkModeDropdown.selection.text === "Custom Watermark File";
        stageDropdown.enabled = !isCustom;
        customDropdown.enabled = isCustom;
    }

    populateCustomDropdown(prefs.watermarkFolder);
    updateWatermarkModeUI();

    optsPanel.add("statictext", undefined, "Position:");
    var positionDropdown = optsPanel.add("dropdownlist", undefined, [
        "Bottom Right",
        "Bottom Left",
        "Top Right",
        "Top Left",
        "Center"
    ]);
    dropdownSelect(positionDropdown, prefs.position);

    var sizeGroup = optsPanel.add("group");
    sizeGroup.add("statictext", undefined, "Size (% image width):");
    var sizeInput = sizeGroup.add("edittext", undefined, prefs.sizePercent);
    sizeInput.characters = 6;

    var opacityGroup = optsPanel.add("group");
    opacityGroup.add("statictext", undefined, "Opacity (%):");
    var opacityInput = opacityGroup.add("edittext", undefined, prefs.opacity);
    opacityInput.characters = 6;

    var paddingGroup = optsPanel.add("group");
    paddingGroup.add("statictext", undefined, "Padding (px):");
    var paddingInput = paddingGroup.add("edittext", undefined, prefs.padding);
    paddingInput.characters = 6;

    var exportPanel = optionsTab.add("panel", undefined, "Export Options");
    exportPanel.orientation = "column";
    exportPanel.alignChildren = "fill";
    exportPanel.margins = 10;

    exportPanel.add("statictext", undefined, "Export Format:");
    var formatDropdown = exportPanel.add("dropdownlist", undefined, ["JPG", "PNG", "PSD"]);
    dropdownSelect(formatDropdown, prefs.format);

    var qualityGroup = exportPanel.add("group");
    qualityGroup.add("statictext", undefined, "JPG Quality 1-12:");
    var qualityInput = qualityGroup.add("edittext", undefined, prefs.quality);
    qualityInput.characters = 6;

    var suffixGroup = exportPanel.add("group");
    suffixGroup.add("statictext", undefined, "Filename Suffix:");
    var suffixInput = suffixGroup.add("edittext", undefined, prefs.suffix);
    suffixInput.characters = 14;

    var previewPanel = optionsTab.add("panel", undefined, "Preview After Saving");
    previewPanel.orientation = "column";
    previewPanel.alignChildren = "fill";
    previewPanel.margins = 10;

    var leaveCurrentCopyOpenCheck = previewPanel.add("checkbox", undefined, "Leave current watermarked copy open after saving");
    leaveCurrentCopyOpenCheck.value = prefs.leaveCurrentCopyOpen !== "false";

    var openBatchSamplesCheck = previewPanel.add("checkbox", undefined, "Open sample results after batch");
    openBatchSamplesCheck.value = prefs.openBatchSamples !== "false";

    var sampleGroup = previewPanel.add("group");
    sampleGroup.add("statictext", undefined, "Batch sample count:");
    var sampleCountInput = sampleGroup.add("edittext", undefined, prefs.batchSampleCount);
    sampleCountInput.characters = 6;

    var legendTab = tabs.add("tab", undefined, "Stage Legend");
    legendTab.orientation = "column";
    legendTab.alignChildren = "fill";
    legendTab.margins = 12;

    var legendText =
        "What is CAHDD?\n\n" +
        "CAHDD stands for Computer Aided Human Designed & Developed. It is a voluntary framework " +
        "for making authorship visible in creative work by indicating how human input, digital tools, " +
        "and AI-assisted processes contribute to the final result.\n\n" +
        "Rather than hiding the process, CAHDD helps creators communicate it clearly and consistently.\n\n" +
        "The framework stages are listed below:\n\n" +

        "0: Traditional Human Craft\n" +
        "Fully human-created, no digital automation.\n\n" +

        "1: Digitally Assisted Creation\n" +
        "Standard digital tools, no AI generation.\n\n" +

        "2: Algorithmic Assistance\n" +
        "Scripts, procedural, parametric, or automated tools.\n\n" +

        "3: Human-AI Hybrid Creation\n" +
        "Human direction with AI generation or enhancement.\n\n" +

        "4: AI-Generated, Human-Curated\n" +
        "Majority AI output, selected and refined by human.\n\n" +

        "5: Fully Autonomous AI Creation\n" +
        "Minimal or no meaningful human creative input.\n\n" +

        "X: Experimental / Unclassified\n" +
        "Complex, unclear, or evolving workflow.";

    var legendBox = legendTab.add("edittext", undefined, legendText, {
        multiline: true,
        scrolling: true,
        readonly: true
    });
    legendBox.preferredSize = [700, 430];

    tabs.selection = setupTab;

    var footer = dlg.add("statictext", undefined, "Powered by CAHDD.org");
    footer.graphics.font = ScriptUI.newFont("Arial", "BOLD", 10);

    var footer2 = dlg.add("statictext", undefined, "Redistribution permitted with attribution. Removal, alteration, or concealment of CAHDD references is prohibited.");
    footer2.characters = 100;

    var btnGroup = dlg.add("group");
    btnGroup.alignment = "right";
    var runBtn = btnGroup.add("button", undefined, "Run");
    var cancelBtn = btnGroup.add("button", undefined, "Cancel");

    watermarkModeDropdown.onChange = function () {
        updateWatermarkModeUI();
    };

    wmBtn.onClick = function () {
        var start = prefs.watermarkFolder && Folder(prefs.watermarkFolder).exists ? Folder(prefs.watermarkFolder) : Folder.myDocuments;
        var f = Folder.selectDialog("Select folder containing CAHDD or custom watermark files", start);
        if (f) {
            prefs.watermarkFolder = f.fsName;
            wmText.text = f.fsName;
            populateCustomDropdown(f.fsName);
        }
    };

    srcBtn.onClick = function () {
        var start = prefs.sourceFolder && Folder(prefs.sourceFolder).exists ? Folder(prefs.sourceFolder) : Folder.myDocuments;
        var f = Folder.selectDialog("Select source folder of images to watermark", start);
        if (f) {
            prefs.sourceFolder = f.fsName;
            srcText.text = f.fsName;

            if (useDefaultOutputCheck.value) {
                var autoOut = new Folder(f.fsName + "/CAHDD_Output");
                prefs.outputFolder = autoOut.fsName;
                outText.text = autoOut.fsName;
            }
        }
    };

    outBtn.onClick = function () {
        var start = prefs.outputFolder && Folder(prefs.outputFolder).exists ? Folder(prefs.outputFolder) : Folder.myDocuments;
        var f = Folder.selectDialog("Select output folder for watermarked copies", start);
        if (f) {
            prefs.outputFolder = f.fsName;
            outText.text = f.fsName;
            useDefaultOutputCheck.value = false;
        }
    };

    useDefaultOutputCheck.onClick = function () {
        if (useDefaultOutputCheck.value) {
            var sourceFolder = new Folder(srcText.text);
            if (sourceFolder.exists) {
                var autoOut = new Folder(sourceFolder.fsName + "/CAHDD_Output");
                prefs.outputFolder = autoOut.fsName;
                outText.text = autoOut.fsName;
            } else {
                outText.text = "Default output folder will be created after source folder is selected";
            }
        } else {
            prefs.outputFolder = "";
            outText.text = "No output folder selected";
        }
    };

    clearOutBtn.onClick = function () {
        prefs.outputFolder = "";
        outText.text = "No output folder selected";
        useDefaultOutputCheck.value = false;
    };

    cancelBtn.onClick = function () {
        dlg.close();
    };

    runBtn.onClick = function () {
        var watermarkFolder = new Folder(wmText.text);

        if (!watermarkFolder.exists) {
            alert("Select a valid watermark folder.");
            return;
        }

        var watermarkFileName;

        if (watermarkModeDropdown.selection.text === "Custom Watermark File") {
            if (!customDropdown.selection) {
                alert("Select a custom watermark file.");
                return;
            }
            watermarkFileName = customDropdown.selection.text;
        } else {
            watermarkFileName = stageDropdown.selection.text;
        }

        var watermarkFile = new File(watermarkFolder.fsName + "/" + watermarkFileName);

        if (!watermarkFile.exists) {
            alert("Watermark file not found:\n\n" + watermarkFile.fsName);
            return;
        }

        var sizePercent = validNumber(sizeInput.text, 4, 0.5, 50);
        var opacity = validNumber(opacityInput.text, 30, 1, 100);
        var padding = validNumber(paddingInput.text, 40, 0, 2000);
        var quality = validNumber(qualityInput.text, 10, 1, 12);
        var suffix = suffixInput.text || "_CAHDD";
        var batchSampleCount = validNumber(sampleCountInput.text, 6, 0, 50);
        var leaveCurrentOpen = leaveCurrentCopyOpenCheck.value;
        var openBatchSamples = openBatchSamplesCheck.value;

        prefs.watermarkFolder = watermarkFolder.fsName;
        prefs.watermarkMode = watermarkModeDropdown.selection.text;
        prefs.stage = stageDropdown.selection.text;
        prefs.customWatermark = customDropdown.selection ? customDropdown.selection.text : "";
        prefs.position = positionDropdown.selection.text;
        prefs.sizePercent = String(sizePercent);
        prefs.opacity = String(opacity);
        prefs.padding = String(padding);
        prefs.mode = modeDropdown.selection.text;
        prefs.format = formatDropdown.selection.text;
        prefs.quality = String(quality);
        prefs.suffix = suffix;
        prefs.useDefaultOutput = useDefaultOutputCheck.value ? "true" : "false";
        prefs.leaveCurrentCopyOpen = leaveCurrentOpen ? "true" : "false";
        prefs.openBatchSamples = openBatchSamples ? "true" : "false";
        prefs.batchSampleCount = String(batchSampleCount);

        var outputFolder = null;

        if (modeDropdown.selection.text === "Batch Folder") {
            var sourceFolder = new Folder(srcText.text);

            if (!sourceFolder.exists) {
                alert("Select a valid source image folder.");
                return;
            }

            if (useDefaultOutputCheck.value) {
                outputFolder = ensureOutputFolder(sourceFolder.fsName + "/CAHDD_Output");
                prefs.outputFolder = outputFolder.fsName;
            } else if (outText.text && outText.text !== "No output folder selected" && outText.text !== "Default output folder will be created after source folder is selected") {
                outputFolder = ensureOutputFolder(outText.text);
                prefs.outputFolder = outputFolder.fsName;
            } else {
                outputFolder = null;
                prefs.outputFolder = "";
            }

            prefs.sourceFolder = sourceFolder.fsName;
            savePrefs(prefs);

            var files = getImageFiles(sourceFolder);

            if (!files.length) {
                alert("No supported image files found in the selected source folder.");
                return;
            }

            var processed = 0;
            var failed = 0;
            var openedSamples = 0;

            for (var i = 0; i < files.length; i++) {
                try {
                    var doc = app.open(files[i]);

                    applyWatermarkToDocument(watermarkFile, watermarkFileName, sizePercent, opacity, padding, prefs.position);

                    saveCopy(doc, outputFolder, files[i], suffix, prefs.format, quality);

                    if (openBatchSamples && openedSamples < batchSampleCount) {
                        openedSamples++;
                        // Leave this watermarked document open as a preview sample.
                    } else {
                        doc.close(SaveOptions.DONOTSAVECHANGES);
                    }

                    processed++;
                } catch (e) {
                    failed++;
                    try {
                        if (app.documents.length) app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
                    } catch (ignore) {}
                }
            }

            dlg.close();
            app.preferences.rulerUnits = originalUnits;

            alert(
                "CAHDD batch watermarking complete.\n\n" +
                "Processed: " + processed + "\n" +
                "Failed: " + failed + "\n" +
                "Preview samples opened: " + openedSamples + "\n\n" +

                "Preview files are open for inspection only.\n" +
                "The saved watermarked files have already been created.\n" +
                "When closing preview files, choose 'No' or 'Don't Save'.\n\n" +

                "Output:\n" +
                (outputFolder ? outputFolder.fsName : "Saved beside original files")
            );

            return;
        }

        if (useDefaultOutputCheck.value) {
            alert("Default CAHDD_Output folder only applies to Batch Folder mode.\n\nFor Current Open Image mode, choose an output folder or use a previously saved document so the copy can save beside the original.");
            return;
        }

        if (outText.text && outText.text !== "No output folder selected" && outText.text !== "Default output folder will be created after source folder is selected") {
            outputFolder = ensureOutputFolder(outText.text);
            prefs.outputFolder = outputFolder.fsName;
        } else {
            outputFolder = null;
            prefs.outputFolder = "";
        }

        savePrefs(prefs);

        var ok = saveCurrentOpenImageCopy(
            watermarkFile,
            watermarkFileName,
            sizePercent,
            opacity,
            padding,
            prefs.position,
            outputFolder,
            suffix,
            prefs.format,
            quality,
            leaveCurrentOpen
        );

        if (ok) {
            dlg.close();
            app.preferences.rulerUnits = originalUnits;

            if (leaveCurrentOpen) {
                alert(
                    "CAHDD watermarked copy saved.\n\n" +
                    "Original open document was left unchanged.\n\n" +
                    "A preview document has been left open for inspection.\n\n" +
                    "The saved watermarked file has already been created.\n" +
                    "When closing the preview, choose 'No' or 'Don't Save'."
                );
            } else {
                alert(
                    "CAHDD watermarked copy saved.\n\n" +
                    "Original open document was left unchanged."
                );
            }
        }
    };

    dlg.show();
    app.preferences.rulerUnits = originalUnits;

})();
