function cr(path)
{
  //app.activeDocument.activeLayer.duplicate();
    var doc=app.activeDocument;
    file = new File(path);
    try
    {
        var curr_file = app.open(file); // error = file format (change to jpg)
        curr_file.selection.selectAll();
        curr_file.selection.copy();
        curr_file.close(SaveOptions.DONOTSAVECHANGES);
        doc.paste();  
        return true;
     }catch(e){
            return false;
     }
}

function read_s(a)
{
    var b = new File(a);
    b.open('r');
    var str = "";
    while(!b.eof)
        str += b.readln();
    b.close();    
    return str;
}

var thisFile = new File($.fileName);  
var basePath = thisFile.path;

var res1=read_s(basePath+"/ExcelScript/files/names.txt");
var names = res1.split("%");

res1=read_s(basePath+"/ExcelScript/files/dept.txt");
var dept=res1.split("%");

res1=read_s(basePath+"/ExcelScript/files/roles.txt");
var role=res1.split("%");

res1=read_s(basePath+"/ExcelScript/files/photo_id.txt");
var photo=res1.split("%");

var i;
for(i=0;i<names.length;i++)
{
    if(role[i]=="Head")
    {
        var fileRef = new File(basePath+"/templates/head.psd")
    }
    else if(role[i]=="Co Head")
    {
        var fileRef = new File(basePath+"/templates/cohead.psd")
    }
    else
    {
        var fileRef = new File(basePath+"/templates/rest.psd")
    }

    var docRef = app.open (fileRef) // error = target application wrong (change to Adobe Photoshop CS6)
    var doc = app.activeDocument;
    
    if(!cr(basePath+ '/photos/' +photo[i])){
        $.writeln(names[i]+"-"+i+" : Skipped"); 
        continue;
    }

    doc.layerSets.getByName("Text").artLayers.getByName("NAME").textItem.contents=names[i];    
    doc.layerSets.getByName("Text").artLayers.getByName("Post").textItem.contents=role[i];
    doc.layerSets.getByName("Text").artLayers.getByName("Department").textItem.contents=dept[i];
    
    var opts, pngFile;
    opts = new PhotoshopSaveOptions();
    pngFile = new File(basePath+"/outputs/psd/"+names[i]+".psd");
    app.activeDocument.saveAs(pngFile, opts,true);
    activeDocument.close(SaveOptions.DONOTSAVECHANGES);
    
    $.writeln(names[i]+"-"+i);    
}