var doc = app.activeDocument;

var layers = doc.layers;

var traces = []

settings = [
    {
        name: "Light",
        color: 0x4d,
        threshold: 128
    },
    {
        name: "Medium",
        color: 0x33,
        threshold: 96
    },
    {
        name: "Dark",
        color: 0x1a,
        threshold: 64
    },
    {
        name: "Black",
        color: 0x00,
        threshold: 128
    }
]

for (var j=0; j<doc.layers.length; j++) {
    var candidate = doc.layers[j];

    if (candidate.name.indexOf("Background") >= 0) {
        candidate.remove()
        break
    }
}

for (var i=0; i<settings.length; i++) {
    var item = settings[i];
    var layer = null;

    for (var j=0; j<doc.layers.length; j++) {
        var candidate = doc.layers[j];

        if (candidate.name.indexOf(item.name) >= 0) {
            layer = candidate;
            break;
        }
    }

    var raster = layer.pageItems[0]
    var pluginRef = raster.trace()
    var trace = pluginRef.tracing
    traces.push(trace)
    var options = trace.tracingOptions

    options.tracingMode = TracingModeType.TRACINGMODEBLACKANDWHITE
    options.threshold = item.threshold
    options.ignoreWhite = true
    options.noiseFidelity = 10
    options.corderFidelity = 0.5
    options.pathFidelity = 75
    options.tracingMethod = TracingMethodType.TRACINGMETHODABUTTING
    options.snapCurvesToLines = false

    traced = trace.expandTracing();

    traces.push(traced);

    var toSet = []

    for (var j=0; j < traced.pathItems.length; j++) {
        toSet.push(traced.pathItems[j])
    }

    for (var j=0; j < traced.compoundPathItems.length; j++) {
        for (var k=0; k < traced.compoundPathItems[j].pathItems.length; k++)
        {
            toSet.push(traced.compoundPathItems[j].pathItems[k])
        }
    }
    
    for (var j=0; j< toSet.length; j++) {
        var thing = toSet[j]
        
        var color = new RGBColor()

        color.red = item.color
        color.green = item.color
        color.blue = item.color

        thing.fillColor = color
    }
}

for (var i = 0; i < traces.length; i++) {
    traces[i].selected = true
}

app.executeMenuCommand("group")

doc.fitArtboardToSelectedArt(0)
