/////////////////////////////////////////////////////////////////////
//  DDS_DXT5_n.js
//
//  Author: Leonardo Covarrubias
//  Date: 02/27/2010
//  Contact: leo.covarrubias@live.com
//  Website: blog.leocov.com - www.leocov.com
//
//
//  Based on: Save As Map.js by Fredrik Brännbacka - 2007-04-12
//
//  Description: Javascript file to export DDS normal map textures with nvcompress - Nvidia Texture Tools 2
/////////////////////////////////////////////////////////////////////

var doc = app.activeDocument;

var imgName= doc.name;
imgName = imgName.substr(0, imgName.length -4);
var newDoc = doc.duplicate();
newDoc.flatten();

var tempDir = Folder.temp;
var docPath = "~/";
if(doc.saved){
  docPath = doc.path;
  newFile = new File(docPath+"/"+imgName+"_DXT5.dds");
//Temp file creation and options
  tmpFile = new File(tempDir+imgName+"_TMP.tga");
  saveOptions = new TargaSaveOptions();
  saveOptions.layers = false;
  saveOptions.alphaChannels = true;
  newDoc.saveAs(tmpFile, saveOptions, true,Extension.LOWERCASE);
  newDoc.close(SaveOptions.DONOTSAVECHANGES);
// This is the program exe and flags
  var commandtoRun = "nvcompress -normal -bc3";
  var commandParms = " \""+tmpFile.fsName+"\" \""+newFile.fsName+"\"";

  //batch file for nvcompress conversion, requires you to have nvcompress.exe's file path in your PATH Environment Variable
  var bat = new File(tempDir+"/conv.bat");

  // write new batch file
  bat.open("w");
  bat.writeln(commandtoRun+commandParms);
  bat.writeln("del /F \""+tmpFile.fsName+"\"");
  bat.writeln("del /F \""+bat.fsName+"\"");
  bat.close();

  if (!bat.exists){
     $.sleep(250);
  };
  bat.execute();
}else{
  newDoc.close(SaveOptions.DONOTSAVECHANGES);
  alert("Image is not Saved!");
}
