var g_oAddinMgr = null;
var g_oContext = null;
var g_oApplet = null;
var g_menuBars = null;
var g_toolBars = null;
var g_menuBars = null;
var ds = null;
var sm = null;
var pm = null;
var wb = null;
var installDir = ""; //Addin installation directory
var MinMeshSize;
var MaxMeshSize;
var NormalAngle;
var GrowthRate;
var Pinch;
var AutoPinch=0;
var NbInflation;
var IsInflationOn;
var VlayerSize=0;
var IbSize;
var IntfVlayerCh;
var IntfCrevicePiston;
var CreviceNoOfLayers;
var ChSize;
var ChamberBottomMeshSize;
var ChGrowthRate;
var VT;
var VCProjectToGeometry = 1;
var MeshType, ProxMinMeshSize, ProxNumCells, ProxValveSize;
var versionPortFlow = "V2";
var versionSectorComb = "SC2";
var versionColdFlow = "C4";
var versionForte = "F1";
var initialPanelValue = "";
var originalNsFaces=0;
var SparkSOI;
var SoiRadius;
var ChInflation=0;

//Add a push method to JScript Array, because its added on 5.5 version
var push = function(){
    for(var i = 0; arguments[ i ] != null; i++)
       this[this.length++] = arguments[ i ];
return( this );
}
Array.prototype.push=push;
// @end 

// You don't need to make any changes in the OnLoad and Unload functions below
function OnLoad(oAddinMgr) {
  try {
    IcOnLoad(oAddinMgr);
  }
  catch (error) {
    if(g_oApplet)
      g_oApplet.Script.WBScript.Out(error.description, true, error.name);
  }
}
function IcOnLoad(oAddinMgr) {
//  debugger;
  g_oAddinMgr = oAddinMgr;
  g_oAddinMgr.OnContextChange.AddCOM(this, "OnContextChange");
  if (g_oAddinMgr.Commander.WB.Title == "Meshing" || g_oAddinMgr.Commander.WB.Title == "") {//for DP title is null
    installDir = g_oAddinMgr.Commander.WB.AISOLCommonFile; 	//"E:\Program Files\ANSYS Inc\v140\AISOL\CommonFiles\"
    installDir = installDir.substring(0, installDir.length - 12);
    installDir += "WBAddins/ICEngineMesh";
   //For Meshing Regeneration, where we need to delete duplicate name selection, and invalid pinches
    var app = g_oAddinMgr.Commander.WB.AppletList.Applet("DSApplet");
    if (app) {
      ds = app.App.Script.ds;
      sm = app.App.Script.sm;
      pm = app.App.Script.pm;
      wb = app.App.Script.wb;
      //ds.OnUserTransactionFinished.AddCOM(this, "ICUserTransactionFinished");
      ds.Script.wbAddinScriptObject = this;
    }
  }
}
function getHydraulicDia(path,nsName) {

var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
    var textStream = fileSys.CreateTextFile(path, true);

    if (typeof (ds.Script.lv) != "undefined")
        ds.Script.lvFroceOutOfEdit();

    var branch = ds.Tree.FirstActiveBranch;
    if (!branch) {
        if (ds.Tree.Branches.Count)
            branch = ds.Tree.Branches.Item(1);
    }
    if (!branch)
        return;
	
  
    var Assys = pm.assemblies;
	var Assy;
    if (!Assys || !Assys.Count) return;
      Assy = Assys.Item(1);


   var ns, nsReq;
	var nsl = branch.Components;
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      var str1 = String(ns.Name);
      if (str1 == nsName)
	  {
        nsReq = ns;
		break;
	  }
    }
 
    ds.UnitSystemID = 0;
    var faceIdArr = new Array();
    var facePartIdArr = new Array();
	var faceArr = new Array();
	
	var areaTotal = 0;
	for (var k = 0; k < nsReq.NumInSelection - nsReq.NumSuppressedItems; k++) {
      str1 = String(nsReq.GetUnsuppressedPartTopoPair(k));
      var pos = str1.indexOf(";");
      var partId = str1.substring(0, pos);
      var topoId = str1.substring(pos + 1);
      var part = Assy.PartById(partId);
      var face = part.BRep.Cell(topoId);
	  faceIdArr.push(topoId);
      facePartIdArr.push(partId);
      faceArr.push(face);
	  
	  //areaTotal = areaTotal + face.Area;
	  areaTotal = areaTotal + IcGetFaceAreaAMPUnits(topoId,partId);
	}
	
	var edgeIdArr = new Array();
    var edgePartIdArr = new Array();
	var edgeArr = new Array();
	
	var edges,faces;
	for (i = 0; i < faceArr.length; ++i){
	   edges = faceArr[i].Edges;
	   for (j = 1; j <= edges.Count; ++j){
	      edgeIdArr.push(edges.item(j).Id);
		  edgePartIdArr.push(facePartIdArr[i]);
		  edgeArr.push(edges.item(j));
	   }
	}

	var lengthTotal = 0;
	for (i = 0; i < edgeArr.length; ++i){
	   faces = edgeArr[i].Faces;
	   
	   var lFlagAddEdge = 0;
	   for (j = 1; j <= faces.Count; ++j){
	      var lFlagFound = 0;
	      for (k = 0; k < faceArr.length; ++k){
		  
		  if(edgePartIdArr[i] != facePartIdArr[k])
		     continue;
		  
		  if(faceIdArr[k] == faces.item(j).Id){
		       lFlagFound = 1;
		       break;
			}
			 
		   //if(faceArr[k] == faces.item(j))
		      //continue;
	      }
		  
		  if(lFlagFound == 0)
		  {
		    lFlagAddEdge = 1;
		    break;
			}
				
	   }
	   
	   if(lFlagAddEdge == 1){
	      //lengthTotal = lengthTotal + edgeArr[i].Length;
		  lengthTotal = lengthTotal + IcGetEdgeLengthAMPUnits(edgeIdArr[i], edgePartIdArr[i])
	   }
	}
	
	var HydDia = 4*areaTotal/lengthTotal;
	var Intensity = 2;
	textStream.WriteLine("Hydraulic Diameter");
    textStream.WriteLine(HydDia);
	textStream.WriteLine(Intensity);
    textStream.Close();
	
	ds.UnitSystemID = 2;
}
function getMeshDetails(path) {

    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
    var textStream = fileSys.CreateTextFile(path, true);

    if (typeof (ds.Script.lv) != "undefined")
        ds.Script.lvFroceOutOfEdit();

    var branch = ds.Tree.FirstActiveBranch;
    if (!branch) {
        if (ds.Tree.Branches.Count)
            branch = ds.Tree.Branches.Item(1);
    }
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

    meshGroup.MeshMetric = 7;
    textStream.WriteLine("MeshData");
    textStream.WriteLine(meshGroup.MeshMetricMax);
    textStream.WriteLine(meshGroup.Elements);
    textStream.Close();
}
function getMeshState(path) {

    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
    var textStream = fileSys.CreateTextFile(path, true);

    if (typeof (ds.Script.lv) != "undefined")
        ds.Script.lvFroceOutOfEdit();

    var branch = ds.Tree.FirstActiveBranch;
    if (!branch) {
        if (ds.Tree.Branches.Count)
            branch = ds.Tree.Branches.Item(1);
    }
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;
		
	textStream.WriteLine("MeshStatus");
   if(meshGroup.MeshingFailed || meshGroup.State != ds.Script.id_Updated)
   {
      textStream.WriteLine("Failed");
   }
   else
   {
      textStream.WriteLine("Updated");
   }
 
    textStream.Close();
}
function getNSList(iOption,path) {
    var NSlist = "";
    
    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
    var textStream = fileSys.CreateTextFile(path, true);
    
    if (ds) {
        var ns, name, found, chNs = null;
        var j = 0;
        var partid, topid, pos;
        var nsl;
        var branch = ds.Tree.FirstActiveBranch;
        if (!branch) {
            if (ds.Tree.Branches.Count)
                branch = ds.Tree.Branches.Item(1);
        }
        if (branch) {
            nsl = branch.Components;
            var ns, nb = 0;
            textStream.WriteLine("Named Selections");
            for (j = 1; j <= nsl.Count; ++j) {
                ns = nsl.item(j);

                if (ns.SendToSolver == false)
                    continue;

                var str1 = String(ns.GetUnsuppressedPartTopoPair(0));
                var pos = str1.indexOf(";");
                var partid = str1.substring(0, pos);
                var topid = str1.substring(pos + 1);

                var topoName;
                var topoType = Math.abs(topid & 0xE0000000);
                if (topoType == 0)
                    topoName = "Vertex";
                else if (topoType == 0x40000000)
                    topoName = "Volume";
                else if (topoType == 0x80000000)
                    topoName = "Face";

                if (iOption == "ns_all") {
                    textStream.WriteLine(ns.Name);
                }
                else if ((iOption == "ns_surface") && (topoName == "Face")) {
                    textStream.WriteLine(ns.Name);
                }
                else if ((iOption == "ns_volume") && (topoName == "Volume")) {
                    textStream.WriteLine(ns.Name);
                }
            }
        }
    }
    textStream.Close();
}
//function getNSList(iOption) {
//    var NSlist = "";
//    //var path = ds.ActiveFile;
//    //var path = ds.ActiveFile;
//    path = "e:\\temp.txt";
//    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
//    var textStream = fileSys.CreateTextFile(path, true);
//    
//    if (ds) {
//        var branch = ds.Tree.FirstActiveBranch;
//        var ns, name, found, chNs = null;
//        var j = 0;
//        var partid, topid, pos;
//        var nsl;
//        if (branch) {
//            nsl = branch.Components;
//            var ns, nb = 0;
//            for (j = 1; j <= nsl.Count; ++j) {
//                ns = nsl.item(j);

//                var str1 = String(ns.GetUnsuppressedPartTopoPair(0));
//                var pos = str1.indexOf(";");
//                var partid = str1.substring(0, pos);
//                var topid = str1.substring(pos + 1);

//                var topoName;
//                var topoType = Math.abs(topid & 0xE0000000);
//                if (topoType == 0)
//                    topoName = "Vertex";
//                else if (topoType == 0x40000000)
//                    topoName = "Volume";
//                else if (topoType == 0x80000000)
//                    topoName = "Face";

//                if (iOption == 0) {
//                    textStream.WriteLine(ns.Name);
//                }
//                else if ((iOption == 1) && (topoName == "Face")) {
//                    textStream.WriteLine(ns.Name);
//                }
//                else if ((iOption == 2) && (topoName == "Volume")) {
//                    textStream.WriteLine(ns.Name);
//                }
//            }
//        }
//    }
//    textStream.Close();
//}
function getNbModifiedNS() {
  if (ds) {
    var branch = ds.Tree.FirstActiveBranch;
    var ns, name, found, chNs = null;
    var j = 0;
    var partid, topid, pos;
    var nsl;
    if (branch) {
      nsl = branch.Components;
      var ns,nb=0;
      for (j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        if (ns.Name == "ib-worksheet")
          break;
        if (ns.NumInSelection == 0)
          continue;
        if (!ns.ImportedFromCAD)
          nb++;
      }
      return nb;
    }
    else
      return 0;
  }
}
function getNbImportedNS() {
  if (ds) {
    var branch = ds.Tree.FirstActiveBranch;
    var ns, name, found, chNs = null;
    var j = 0;
    var partid, topid, pos;
    var nsl;
    if (branch) {
      nsl = branch.Components;
      var ns, nb = 0;
      for (j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
//        if (ns.NumInSelection == 0)
//          continue;
        if (ns.ImportedFromCAD)
          nb++;
      }
      return nb;
    }
    else
      return 0;
  }
}
function getNbDuplicateNS() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns1, ns2, arr;
  var i = 0; j = 0;
  var nsl;
  arr = new Array();
  var count = 0;

  nsl = branch.Components;
  for (j = nsl.Count; j >= 1; --j) {
    ns1 = nsl.item(j);
    if (!ns1.ImportedFromCAD)
      break;
    for (i = 1; i < j; ++i) {
      ns2 = nsl.item(i);
      if (ns1.Name == ns2.Name)
        break;
    }
    if (i < j) {
      count++;
    }
  }
  return count;
}
function getNbNS() {
  if (ds) {
    var branch = ds.Tree.FirstActiveBranch;
    var ns, name, found, chNs = null;
    var j = 0;
    var partid, topid, pos;
    var nsl;
    if (branch) {
      nsl = branch.Components;
      return nsl.Count;
    }
    else
      return 0;
  }
}

function ICUserTransactionFinished() {
  try {
    IcRegenerate();
  }
  catch (error) {
    if (g_oApplet)
      g_oApplet.Script.WBScript.Out(error.description, true, error.name);
  }
}
function IcRegenerate() {
    //Remove the call back for non IC meshing applications
 
  var IsICE = IsICEDoc();
  if (IsICE == -1) // Document not yet loaded
    return;
  if (IsICE == 0) {
    ds.OnUserTransactionFinished.RemoveCOM(this, "ICUserTransactionFinished");
	  return;
  }

  //ds.Script.currentUnitSysID = this;
  return; //Return from here when we regenerate through Meshing Addin.
  if (IsPortFlow()) {
    if (!ds.Tree.FirstActiveBranch) return;
    if (!ds.Tree.FirstActiveBranch.MeshControlGroup) return;
  
    var strprev = ICGetSessionVaribale("ICEngineValveLiftPlaneOff");
    var strcurr = GetPortFlowSessionVariableString();
    if (IsAllNSImported() && (strprev != strcurr) && (strprev != "")) {
      ICRegenratePortFlow();
      ICSetSessionVaribale("ICEngineValveLiftPlaneOff", strcurr);
    }
    return;
  }
  
  
  if (IsCombustion()) {
    if (!ds.Tree.FirstActiveBranch) return;
    if (!ds.Tree.FirstActiveBranch.MeshControlGroup) return;
 
    if (IsAllNSImportedSector()) {
      ICRegenrateSector();
    }
    return;
  }
    
  //If the name selection is created by user inside Meshing, then we should not call our regeneration code.
  var ActiveObj = ds.Tree.FirstActiveObject;
  if (ActiveObj) {
    if (ActiveObj.Class != ds.Script.id_Model)
      return;
  }

  if(!ds.Tree.FirstActiveBranch) return;
  if (!ds.Tree.FirstActiveBranch.MeshControlGroup) return;
  if (IsNew())
    return;

  //If we execute this method, then this method(callback) is not called after importing duplicate named selection, need to check more
//    var strprev = ICGetSessionVaribale("ICEngineValveLifts");
//    var strcurr = getValveLiftsAttributeString();
//    if ((strprev != strcurr) && (strprev != "")) {
//      ICRegenrateColdFlow();
//      ICSetSessionVaribale("ICEngineValveLifts", strcurr);
//    }
  var tmpNb = getNbNS();
  if (tmpNb > 0) {
    var found = -1;
 	  var j=0;
    while (ds.UserSettings) {
      key = ds.UserSettings.GetSessionVariableKey(j);
      if (key == "")
        break;
      if (key == "ICNumberOfNS")
        found = j;
      j++;
    }
    var attNb = 0;
    if (found >= 0)
      attNb = ds.UserSettings.GetSessionVariableValue(found);
    else{
      ds.UserSettings.AddSessionVariable("ICNumberOfNS", tmpNb);
      return;
    }
    attNb = new Number(attNb);
      
    //If number of name selection changes, then we should call regenerate method.
    if (tmpNb != attNb) {
      var nsl = ds.Tree.FirstActiveBranch.Components;
      if (nsl.Count) {
        var ns = nsl.item(nsl.Count);
        //Do not delete the name selection whose name is not assigned and geometry supports are not defined. Second time it has proper loop.
        //(used if you double click on Mesh cell and click Yes on use modified geometry or if you Update the mesh cell)
        if ((ns.name == "Selection") && (ns.GeometrySelectionString == "No Selection"))
          return;
      }
      var modifNS = getNbModifiedNS();
      var importNS = getNbImportedNS();
      //var nbDuplicates = getNbDuplicateNS();
      var NumNs = 0;
      NumNs = ICGetNumExportNS();
      //if (modifNS == nbDuplicates)-This is previous condition
      if (NumNs <= importNS){
        if (found >= 0)
          ds.UserSettings.DeleteSessionVariable(found);
        ICDeleteDuplicateNS();
        ICRegenrateColdFlow();
        nsl = ds.Tree.FirstActiveBranch.Components;
        ds.UserSettings.AddSessionVariable("ICNumberOfNS", nsl.Count);
      }
    }
  }
  
}
function ICRegenratePortFlow() {
  //Set the units to mm
  ds.UnitSystemID = 2; 

  ICProximitySizing(1);
  ICChamberSizing(1);
  ICPortSizing(1);
  ResetProximityFaceSizing();
  ResetChSweepPortFlow();
  ICCreateUpdateInflationControl(1);
  ICResetNSForBodies();
  
  var branch = ds.Tree.FirstActiveBranch;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  //We need to suppress the Pinch controls whose supports are lost in regeneration
  for (j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_Merge) //suppress only Pinch controls
      continue;
    if (ds.Script.id_FullyDefined != meshctrl.State) {
      if (meshctrl.SubValue)
        meshctrl.SubValue = false;
    }
  }
  var MessageDatabase = ds.Tree.MessageDatabase;
  if (MessageDatabase)
    MessageDatabase.Clear();
}
function ICDeleteDuplicateNS() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns1, ns2, arr;
  var i = 0; j = 0;
  var nsl;
  arr = new Array();

  nsl = branch.Components;
  for (j=nsl.Count; j >= 1 ; --j) {
    ns1 = nsl.item(j);
    for (i = 1; i < j; ++i) {
      ns2 = nsl.item(i);
      if (ns1.Name == ns2.Name)
        break;
    }
	
    //Delete the name selection with the same name as in old name selection (used if Refresh Geometry is called inside Meshing)
    if (i < j) {
	  ICCopyFacesDuplicateNS(ns1,ns2);
      //delete the ns2, if it does not contain any selection
      if (ns2.NumInSelection == 0)
        arr.push(ns2.ID);
      else     //delete the ns1
        arr.push(ns1.ID);
    }
    else if (!ns1.ImportedFromCAD)
      break;    
  }
  if (arr.length) {
    for (j = 0; j < arr.length; j++) {
      if (ds.Tree.CanDelete(arr[j]))
        ds.Tree.DeleteItem(arr[j]);
    }
    //Delete the name selection which does not have any support, in case of piston type3, we get cyl-quad with 0 supprots when we change from 180 to 0
    nsl = branch.Components;
    for (j = nsl.Count; j >= 1; --j) {
      ns1 = nsl.item(j);
      if (ns1.NumInSelection) continue;
      if (ds.Tree.CanDelete(ns1.ID))
        ds.Tree.DeleteItem(ns1.ID);
    }
  }
}
function ICCopyFacesDuplicateNS(ns1,ns2){

   var str1 = String(ns1.Name);
   var str2 = str1.substring(0, 7);
   var flagProceed = 0;
   //if (((str2.indexOf("invalve") != -1) || (str2.indexOf("exvalve") != -1)) && ((str1.indexOf("-ib") != -1)))
   //{
     //flagProceed = 1;
   //}
   
   //if(flagProceed == 0)
   //{
      //return;
   //}
  var nsImported;
  var nsManual;
  var branch = ds.Tree.FirstActiveBranch;
  if(ns1.ImportedFromCAD)
  {
    nsImported = ns1;
    nsManual = ns2;
  }
  else if(ns2.ImportedFromCAD)
  {
    nsImported = ns2;
    nsManual = ns1;
  }
  else
  {
    return;
  }
  
  sm.Clear();
    for (i = 0; i < nsManual.NumInSelection - nsManual.NumSuppressedItems; i++) {
        str1 = String(nsManual.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        sm.AddToSelection(partid, topid, false);
	}
	
	for (i = 0; i < nsImported.NumInSelection - nsImported.NumSuppressedItems; i++) {
        str1 = String(nsImported.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        sm.AddToSelection(partid, topid, false);
	}
	
	nsManual.GeometrySelection = sm;

}
function CreateVCIB() {

    
    var branch = ds.Tree.FirstActiveBranch;
    var ns1, ns2, arr;
    var i = 0; j = 0;
    var nsl;	
    nsl = branch.Components;
		
	for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if (((str2.indexOf("invalve") != -1) || (str2.indexOf("exvalve") != -1)) && ((str1.indexOf("-ib") != -1))) {
      var partIds = new Array();
      var topoIds = new Array();
	  for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        partIds.push(str1.substring(0, pos));
        topoIds.push(topid = str1.substring(pos + 1));
      }
	if (partIds.length == 0) continue;
    ICCreateVirtualCellForNS(ns, topoIds, partIds);
	break;
    }
  }
  
  //Suppressing related pinches
  var meshGroup = branch.MeshControlGroup;
    var mehctrls = meshGroup.MeshControls;
    var meshctrl, protoList;
    //We need to suppress the Pinch controls whose supports are lost in regeneration
	
	
    for (j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      if (meshctrl.ControlType != ds.Script.id_Merge) //suppress only Pinch controls
        continue;
      protoList = meshctrl.Prototypes;
	  str1 = String(meshctrl.AttatchedSourceName);
      str2 = str1.substring(0, 7);
      if (((str2.indexOf("invalve") != -1) || (str2.indexOf("exvalve") != -1)) && ((str1.indexOf("-ib") != -1))) {
        if (meshctrl.SubValue)
          meshctrl.SubValue = false;
      }
    }
  
  
}
function ICRegenrateColdFlow() {
  var branch = ds.Tree.FirstActiveBranch;
  var i = 0; j = 0;

  //Set the units to mm
  ds.UnitSystemID = 2; 
    IceShowAllParts();
    CreateVCIB();
    ICECreateVirtualEdges(0,1); //for Vlayer and IB
    ICDefineIBMesh(1);
    ICDefineVlayerMesh(1);
    //ICECreateVCforDomeSliverFaces(true);
    ResetChLowerEdges();
    ResetChamberCntrls();

    //Need to reset the valve-port NS, for DE43986
    ResetPortNS();
    var facesArr, partArr, bodiesArr, wallfaceArr, wallPartArr, wallNSArr;
    facesArr = new Array();
    partArr = new Array();
    bodiesArr = new Array();
    wallfaceArr = new Array();
    wallPartArr = new Array();
    wallNSArr = new Array();
    DefineOrResetPortInflationCtrl(facesArr, partArr, bodiesArr, wallfaceArr, wallPartArr, wallNSArr);
    ResetPortSweepCntrl();

    //DE34020 regeneration is making project to underlying no
    ICProjectToUnderlyingGeomVC();
    
    var meshGroup = branch.MeshControlGroup;
    var mehctrls = meshGroup.MeshControls;
    var meshctrl, protoList;
    //We need to suppress the Pinch controls whose supports are lost in regeneration
    if(IsSingleZoneTopo()){
      ICDefineValveSeatFaceSizing();
      ICDefineSingleZoneInflation(1);
    }
    else{
      ICEDefineChamberInflation(1);
    }
    ICEAddSparkCoordinateSystems();
    ICEDefineSparkBOIMesh(1);
	
    for (j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      if (meshctrl.ControlType != ds.Script.id_Merge) //suppress only Pinch controls
        continue;
      protoList = meshctrl.Prototypes;
      if ((ds.Script.id_FullyDefined != meshctrl.State) || (!protoList.Count)) {
        if (meshctrl.SubValue)
          meshctrl.SubValue = false;
      }
    }
    var MessageDatabase = ds.Tree.MessageDatabase;
    if(MessageDatabase)
      MessageDatabase.Clear();
}

// The user buttons are added in function: OnContextChange
function OnContextChange(sender, args) {
  try {
    IcOnContextChange(sender, args);
  }
  catch (error) {
    if (g_oApplet)
      g_oApplet.Script.WBScript.Out(error.description, true, error.name);
  }
}
function IcOnContextChange(sender, args) {
  g_oContext = args.Context;
  if (g_oContext.Name == "WB.DSApplet")
  {
	  g_oApplet = g_oContext.Item("WB.Applet");

	  // Store the DS and WB objects
	  ds = sender.Commander.WB.AppletList.Applet("DSApplet").App.Script.ds;
	  sm = sender.Commander.WB.AppletList.Applet("DSApplet").App.Script.sm;
	  pm = sender.Commander.WB.AppletList.Applet("DSApplet").App.Script.pm;
	  wb = sender.Commander.WB.AppletList.Applet("DSApplet").App.Script.wb;
  	
	  g_toolBars = g_oContext.Item("WB.Applet.ToolBars");
	  g_menuBars = g_oContext.Item("WB.Applet.MenuBars");
    // Callback to add toolbars for ICE
	  //ds.OnProcessingStateFinished.AddCOM(this, "ICEAddToolBar");
	}
}
function ICEAddToolBar() {
  try {
    IcAddMeshingToolBar();
  }
  catch (error) {
    if (g_oApplet)
      g_oApplet.Script.WBScript.Out(error.description, true, error.name);
  }
}
function IcAddMeshingToolBar() {
  var IsICE = 1/*IsICEDoc()*/;
  if (IsICE == -1) // Document not yet loaded
    return;
  if (!g_toolBars) return;
  if (IsICE > 0) {
    var tb, found = false;
    for (var i = g_toolBars.Count; i >= 1; --i) {
      tb = g_toolBars.Item(i);
      if (tb.Caption == "ICEngineMeshingToolbar") {
        found = true;
        break;
      }
    }
    if (found) return;
    var imageDir = installDir + "/images";
    // images from this folder will be used
    var macrotoolbar = g_toolBars.Add("ICEngineMeshingToolbar", "IC Engine");
    macrotoolbar.DisplayButtonText = true;
    var g_oImageList = AnsObjectFactory.CreateDispatchObject("WBControls.WBImageList.182");
    if (g_oImageList.Count) 
      return;
    g_oImageList.Create();
    g_oImageList.Add(imageDir);
    macrotoolbar.ImageList = g_oImageList;

    var buttons = macrotoolbar.Buttons;
    var button1 = buttons.AddButton(101,
					      "SetupMesh",
					      30001,
					      "ICMeshing",
					      false,
					      "Setup Mesh",
					      "IC Setup Mesh");
    button1.Text = "Setup Mesh";
    button1.Tag = "Setup Mesh";

    button1.OnClick.AddCOM(this, "button_OnClick1");
    var button1 = buttons.AddButton(101,
					      "GenerateMesh",
					      30002,
					      "ICUpdate",
					      false,
					      "Generate Mesh",
					      "IC Generate Mesh");
    //Add a function call to this button
    button1.Text = "Generate Mesh";
    button1.Tag = "Generate Mesh";
    button1.OnClick.AddCOM(this, "doICEGenerateMesh");

  }
  else {
    var tb, found = false;
    for (var i = g_toolBars.Count; i >= 1; --i) {
      tb = g_toolBars.Item(i);
      if (tb.Caption == "ICEngineMeshingToolbar") {
        g_toolBars.Remove(i);
        break;
      }
    }
  }
  //ds.OnProcessingStateFinished.RemoveCOM(this, "ICEAddToolBar");
  //ds.Script.currentUnitSysID = this;
}
function IsICEDoc() {
  var IsICEDoc = -1; // -1 for unknown, 0 for non-ic case, 1 for ic case.
//  if (!ds.Tree.Branches)
//    return IsICEDoc;

//  var branch = null;
//  if (ds.Tree.Branches.Count)
//    branch = ds.Tree.Branches.Item(1);
  var branch = ICGetModel();
  if (branch && branch.PrototypeGroup) {
    var attrKey = branch.PrototypeGroup.CADAttribPrefixes;
    if (typeof (attrKey) != "undefined") {
      if (attrKey.indexOf("ICEngine") > -1)
        IsICEDoc = 1;
      else
        IsICEDoc = 0;
    }
    //Commenting the following section because of DE115329
    /*var cadPath = branch.PrototypeGroup.CADFile; 
    //if(branch.PrototypeGroup.Parent && branch.PrototypeGroup.Parent.SystemCaption == "ICE")
    if((cadPath.search("\ICE") > -1)||(cadPath.search("/ICE") > -1))
    {
        IsICEDoc = 1;
    }*/
  }
  return IsICEDoc;
}
function ICGetModel()
{
  var model = null;
  if(!ds.Tree)
    return model;
  if (ds.Tree.Branches && (ds.Tree.Branches.Count > 0))
  {
    model = ds.Tree.Branches.Item(1);
  }
  else if(ds.Tree.Projects && (ds.Tree.Projects.Count>0))
  {
    var project = ds.Tree.Projects.Item(1);
    if(project && project.Models && (project.Models.Count>0))
      model = project.Models.Item(1);
  }
  return model;
}
function ICGetSessionVaribale(varName) {
  var lreturn = "";
  var j = 0;
  var found = -1;
  while (ds.UserSettings) {
    var key = ds.UserSettings.GetSessionVariableKey(j);
    if (key == "")
      break;
    if (key == varName)
      found = j;
    j++;
  }
  if (found >= 0)
    lreturn = ds.UserSettings.GetSessionVariableValue(found);

  return lreturn;
}
function ICSetSessionVaribale(varName,varValue) {
  var lreturn = "";
  var j = 0;
  var found = -1;
  while (ds.UserSettings) {
    key = ds.UserSettings.GetSessionVariableKey(j);
    if (key == "")
      break;
    if (key == varName)
      found = j;
    j++;
  }
  if (found >= 0)
    ds.UserSettings.DeleteSessionVariable(found);
  ds.UserSettings.AddSessionVariable(varName, varValue);
}
function ICDeleteSessionVaribale(varName) {
  var lreturn = "";
  var j = 0;
  var found = -1;
  while (ds.UserSettings) {
    key = ds.UserSettings.GetSessionVariableKey(j);
    if (key == "")
      break;
    if (key == varName)
      found = j;
    j++;
  }
  if (found >= 0)
    ds.UserSettings.DeleteSessionVariable(varName);
}

// Define Methods associated with the buttons
function ReadValueOfString(s) {
  var pos = s.search(">");
  var str1,strR="";
  if (pos > -1) {
    str1 = s.substring(pos + 1);
    pos = str1.search("<");
    if (pos > -1) {
      strR = str1.substring(0,pos);
    }
  }
  return strR;
}
function button_OnClick1() {
  try{
    ICSetupMesh();
  }
  catch (error) {
    if (g_oApplet)
      g_oApplet.Script.WBScript.Out(error.description, true, error.name);
  }
}
function ICSetupMesh() {
  var htmdlg = g_oApplet.Script.AnsObjectFactory.CreateDispatchObject(
	"WBControls.WBHTMLDialog.182");
  var xfer = g_oApplet.Script.AnsObjectFactory.CreateDispatchObject(
	"WBControls.DlgArgs.182");

  var solver = ICGetSessionVaribale("ICESolver");
  if(solver=="Forte"){
    // Display a HTML dialog to accept user name
    var dialog_title = "IC Engine Mesh Parameters";
    var htmurl = installDir + "/html/ICEngineFortePanel.htm";
    htmdlg.AllowResize = true;
   
    var panel = ICGetSessionVaribale("ICEnginePanel");
    initialPanelValue = panel;

    xfer("DefaultMeshSize") = getMeshSize();
    xfer("DefaultChamberMeshSize") = getChmaberBottomMeshSize();

    if (panel == "") {
      xfer("MeshType") = "";
      xfer("RefSize") = getMeshSize();
      xfer("MinMeshSize") = "";
      xfer("MaxMeshSize") = "";
    }
    else {
      ICConvertPanelStringFormat();
      var panel = ICGetSessionVaribale("ICEnginePanel");
      ICTokenizeAndLoadXfers(xfer,panel);
    }
    xfer("IsRefSizeParameter")=ICGetSessionVaribale("ICEIsRefSizeParameter");

    var ok = htmdlg.DoDialog(g_oApplet.Script.wb.hWnd,
			      htmurl,
			      xfer,
			      false,
			      300, 280,
			      7,
			      dialog_title);

    if (ok == 1) // If "OK" button is pressed
    {
      MeshType = new Number(xfer("MeshType"));
      RefSize = new Number(xfer("RefSize"));
      MinMeshSize = new Number(xfer("MinMeshSize"));
      MaxMeshSize = new Number(xfer("MaxMeshSize"));
      var previousSettings = ICGetSessionVaribale("ICEnginePanel");
      ICSetPanelSessionVarFromGlobalVars();
      ICWriteSettingsFileForAddin();

      var newSettings = ICGetSessionVaribale("ICEnginePanel");
      if(!ICAreStringsSameAfterTokenizing(newSettings,previousSettings,";") || IsNew())
        ICEForteAMGSetup();
    }    
    return;
  }    
  else if (IsCombustion()) {


    // Display a HTML dialog to accept user name
    var dialog_title = "IC Sector Mesh Parameters";
    var htmurl = installDir + "/html/ICEngineSectorCombPanel.htm";
    htmdlg.AllowResize = true;
   
    var panel = ICGetSessionVaribale("ICEnginePanel");
    initialPanelValue = panel;

    xfer("DefaultMeshSize") = getMeshSize();
    xfer("DefaultChamberMeshSize") = getChmaberBottomMeshSize();

    if (panel == "") {
      xfer("MeshType") = "";
      xfer("RefSize") = getMeshSize();
      xfer("MinMeshSize") = "";
      xfer("MaxMeshSize") = "";
      xfer("ChamberBottomMeshSize") = getChmaberBottomMeshSize();
      xfer("NbInflation") = "3";
    }
    else {
      ICConvertPanelStringFormat();
      var panel = ICGetSessionVaribale("ICEnginePanel");
      ICTokenizeAndLoadXfers(xfer,panel);
    }
    xfer("IsRefSizeParameter")=ICGetSessionVaribale("ICEIsRefSizeParameter");

    var ok = htmdlg.DoDialog(g_oApplet.Script.wb.hWnd,
			      htmurl,
			      xfer,
			      false,
			      300, 280,
			      7,
			      dialog_title);

    if (ok == 1) // If "OK" button is pressed
    {
      MeshType = new Number(xfer("MeshType"));
      RefSize = new Number(xfer("RefSize"));
      MinMeshSize = new Number(xfer("MinMeshSize"));
      MaxMeshSize = new Number(xfer("MaxMeshSize"));
      NbInflation = new Number(xfer("NbInflation"));
      ChamberBottomMeshSize = new Number(xfer("ChamberBottomMeshSize"));
      IsInflationOn = new Number(xfer("IsInflationOn"));
      ICSetPanelSessionVarFromGlobalVars();
      ICWriteSettingsFileForAddin();
      DefineSectorCombMesh();
    }
    return;
  }
  else if (IsPortFlow()) {
    // Display a HTML dialog to accept user name
    var dialog_title = "IC Port Mesh Parameters";
    var htmurl = installDir + "/html/ICEnginePortFlowPanel.htm";
    htmdlg.AllowResize = true;

    var panel = ICGetSessionVaribale("ICEnginePanel");
    initialPanelValue = panel;

    xfer("DefaultMeshSize") = getMeshSize();
    var valveLifts = getValveLifts();
    var minLift = 0.;
    for (var i = 0; i < (valveLifts.length)/2; ++i) {
      if (i == 0)
        minLift = valveLifts[2 * i + 1];
      else if(minLift > valveLifts[2 * i + 1])
        minLift = valveLifts[2 * i + 1];
    }
    xfer("Lift") = minLift;
    if (panel == "") {
      xfer("MeshType") = "";
      xfer("RefSize") = getMeshSize();
      xfer("MinMeshSize") = "";
      xfer("ProxMinMeshSize") = "";
      xfer("MaxMeshSize") = "";
      xfer("NormalAngle") = "";
      xfer("ProxNumCells") = "";
      xfer("GrowthRate") = "";
      xfer("Pinch") = "";
      xfer("NbInflation") = "";
      xfer("ChSize") = "";
      xfer("ChGrowthRate") = "";
      xfer("ProxValveSize") = "";
    }
    else {
      ICConvertPanelStringFormat();
      var panel = ICGetSessionVaribale("ICEnginePanel");
      ICTokenizeAndLoadXfers(xfer,panel);
    }
    xfer("IsRefSizeParameter")=ICGetSessionVaribale("ICEIsRefSizeParameter");
    
    var ok = htmdlg.DoDialog (g_oApplet.Script.wb.hWnd,
			      htmurl,
			      xfer,
			      false,
			      400, 500,
			      7,
			      dialog_title);

    if (ok == 1) // If "OK" button is pressed
    {
      MeshType = new Number(xfer("MeshType"));
      RefSize = new Number(xfer("RefSize"));
      MinMeshSize = new Number(xfer("MinMeshSize"));
      ProxMinMeshSize = new Number(xfer("ProxMinMeshSize"));
      MaxMeshSize = new Number(xfer("MaxMeshSize"));
      NormalAngle = new Number(xfer("NormalAngle"));
      ProxNumCells = new Number(xfer("ProxNumCells"));
      GrowthRate = new Number(xfer("GrowthRate"));
      Pinch = new Number(xfer("Pinch"));
      NbInflation = new Number(xfer("NbInflation"));
      ChSize = new Number(xfer("ChSize"));
      ChGrowthRate = new Number(xfer("ChGrowthRate"));
      ProxValveSize = new Number(xfer("ProxValveSize"));

      ICSetPanelSessionVarFromGlobalVars();
      ICWriteSettingsFileForAddin();
      DefinePortFlowMesh();
    }
    return;
  }
  // Display a HTML dialog to accept user name
    var htmdlg = g_oApplet.Script.AnsObjectFactory.CreateDispatchObject(
	"WBControls.WBHTMLDialog.182");
    var xfer = g_oApplet.Script.AnsObjectFactory.CreateDispatchObject(
	"WBControls.DlgArgs.182");
    
    var dialog_title= "IC Mesh Parameters";
    var htmurl = installDir + "/html/ICEngineMeshingPanel.htm";

    htmdlg.AllowResize = true;

    // These arguments will be populated from the HTML dialog
    //Write file
    var path = ds.ActiveFile;
    if (path != "") {
      path = path.substring(0, path.length - 5);
      path = path + "xml";
    }
    else {
      path = ds.Tree.FirstActiveBranch.PrototypeGroup.CADFile;
      var pos=-1;
      if (ds.Script.platform == "UNIX")
        pos = path.indexOf("ICE/DM");
      else
        pos = path.indexOf("ICE\\DM");
      if (pos > 0) {
        path = path.substring(0, pos);
        path = path + "global/MECH/ICE.xml";
      }
      else {
        path = "";
      }
    }


    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject"); 

    //Read File
    //var xmlDoc = CreateActiveXObject("Microsoft.XMLDOM");
    xfer("DefaultMeshSize") = getMeshSize();
    xfer("FluentOldApproach") = getFluentOldApproach();
    var containPorts = DoesItContainPorts();
    var singleZoneTopo=0;
    if(IsSingleZoneTopo()){
      containPorts = 1;
      singleZoneTopo=1;
    }
    xfer("SingleZoneTopo") = singleZoneTopo;
    xfer("ContainPorts") = containPorts;
    var containCrevice = DoesItContainCrevice();
    xfer("ContainCrevice") = containCrevice;
    xfer("AutoPinch") = AutoPinch;
    xfer("CreviceMeshSizeAttr") = getCreviceMeshSize();
    xfer("ContainSparkPoint") = isSparkCenterAttrDefined();
    if(IsStraightValveEngine())
      xfer("IsStraightValveEngine") = "1";
    else
      xfer("IsStraightValveEngine") = "0";
    if ((isSparkCenterAttrDefined()>0) && (checkSparkActivateAngles() > 0))
      SparkSOI = 1;
    else 
      SparkSOI = 0;
    xfer("SparkSOI") = SparkSOI;
    if(IsNew())
      xfer("IsNew")=1;
    else
      xfer("IsNew")=0;    
    var useDefault = 1;
    var panel = ICGetSessionVaribale("ICEnginePanel");
    initialPanelValue = panel;
    if (panel != "") {
      useDefault = 0;
      ICConvertPanelStringFormat();
      var panel = ICGetSessionVaribale("ICEnginePanel");
      ICTokenizeAndLoadXfers(xfer,panel);
    }
    else if ((!IsNew()) && (fileSys.FileExists(path))) {
      useDefault = 0;
      if (ds.Script.platform == "UNIX") {
        var ForReading = 1;
        var f = fileSys.GetFile(path);
        var TristateUseDefault = -1;//unicode
        var ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
        var s = ts.ReadLine();
        while (s != "") {
          if (ts.AtEndOfStream)
            break;
          s = ts.ReadLine();
          if (s.length < 2) continue;
          if ((s.search("MeshType") != -1))
            xfer("MeshType") = ReadValueOfString(s);
          else if ((s.search("minMeshSize") != -1))
            xfer("MinMeshSize") = ReadValueOfString(s);
          else if ((s.search("maxMeshSize") != -1))
            xfer("MaxMeshSize") = ReadValueOfString(s);
          else if ((s.search("MeshSize") != -1))
            xfer("RefSize") = ReadValueOfString(s);
          else if ((s.search("normalAngle") != -1)) 
            xfer("NormalAngle") = ReadValueOfString(s);
          else if ((s.search("growthRate") != -1))
            xfer("GrowthRate") = ReadValueOfString(s);
          else if ((s.search("pinch") != -1))
            xfer("Pinch") = ReadValueOfString(s);
          else if ((s.search("inflation") != -1))
            xfer("NbInflation") = ReadValueOfString(s);
          else if ((s.search("vlayerSize") != -1))
            xfer("VlayerSize") = ReadValueOfString(s);
          else if ((s.search("ibSize") != -1))
            xfer("IbSize") = ReadValueOfString(s);
          else if ((s.search("intfVlayerCh") != -1))
            xfer("IntfVlayerCh") = ReadValueOfString(s);
          else if ((s.search("chSize") != -1))
            xfer("ChSize") = ReadValueOfString(s);
          else if ((s.search("chGrowthRate") != -1))
            xfer("ChGrowthRate") = ReadValueOfString(s);
          else if ((s.search("VT") != -1))
            xfer("VT") = ReadValueOfString(s);
        }
        ts.Close();
      }
      else {
        var xmlDoc = AnsObjectFactory.CreateDispatchObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        if (xmlDoc.load(path) && xmlDoc.documentElement.childNodes.length > 12) {
          if (xmlDoc.documentElement.childNodes[0].getAttribute("id") == "MeshType")
            xfer("MeshType") = xmlDoc.documentElement.childNodes[0].text;
          if (xmlDoc.documentElement.childNodes[1].getAttribute("id") == "MeshSize")
            xfer("RefSize") = xmlDoc.documentElement.childNodes[1].text;
          if (xmlDoc.documentElement.childNodes[2].getAttribute("id") == "minMeshSize")
            xfer("MinMeshSize") = xmlDoc.documentElement.childNodes[2].text;
          if (xmlDoc.documentElement.childNodes[3].getAttribute("id") == "maxMeshSize")
            xfer("MaxMeshSize") = xmlDoc.documentElement.childNodes[3].text;
          if (xmlDoc.documentElement.childNodes[4].getAttribute("id") == "normalAngle")
            xfer("NormalAngle") = xmlDoc.documentElement.childNodes[4].text;
          if (xmlDoc.documentElement.childNodes[5].getAttribute("id") == "growthRate")
            xfer("GrowthRate") = xmlDoc.documentElement.childNodes[5].text;
          if (xmlDoc.documentElement.childNodes[6].getAttribute("id") == "pinch")
            xfer("Pinch") = xmlDoc.documentElement.childNodes[6].text;
          if (xmlDoc.documentElement.childNodes[7].getAttribute("id") == "inflation")
            xfer("NbInflation") = xmlDoc.documentElement.childNodes[7].text;
          if (xmlDoc.documentElement.childNodes[8].getAttribute("id") == "vlayerSize")
            xfer("VlayerSize") = xmlDoc.documentElement.childNodes[8].text;
          if (xmlDoc.documentElement.childNodes[9].getAttribute("id") == "ibSize")
            xfer("IbSize") = xmlDoc.documentElement.childNodes[9].text;
          if (xmlDoc.documentElement.childNodes[10].getAttribute("id") == "intfVlayerCh")
            xfer("IntfVlayerCh") = xmlDoc.documentElement.childNodes[10].text;
          if (xmlDoc.documentElement.childNodes[11].getAttribute("id") == "chSize")
            xfer("ChSize") = xmlDoc.documentElement.childNodes[11].text;
          if (xmlDoc.documentElement.childNodes[12].getAttribute("id") == "chGrowthRate")
            xfer("ChGrowthRate") = xmlDoc.documentElement.childNodes[12].text;
          if (xmlDoc.documentElement.childNodes[13].getAttribute("id") == "VT")
            xfer("VT") = xmlDoc.documentElement.childNodes[13].text;
        }
        else
          useDefault = 1;
      }
    }
    if(useDefault) {
      xfer("MeshType") = "";
      xfer("RefSize") = getMeshSize();
      xfer("MinMeshSize") = "";
      xfer("MaxMeshSize") = "";
      xfer("NormalAngle") = "";
      xfer("GrowthRate") = "";
      xfer("Pinch") = "";
      xfer("NbInflation") = "";
      xfer("VlayerSize") = "";
      xfer("IbSize") = "";
      xfer("IntfVlayerCh") = "";
      xfer("ChSize") = "";
      xfer("ChGrowthRate") = "";
      xfer("VT") = "";
      xfer("AutoPinch") = "0";
      xfer("IntfCrevicePiston") = getCreviceMeshSize();
      xfer("SparkSOI") = SparkSOI;
    }
    xfer("IsRefSizeParameter")=ICGetSessionVaribale("ICEIsRefSizeParameter");
    var height=525,width=400;
    if(!containPorts)
        height=400;
    var ok = htmdlg.DoDialog (g_oApplet.Script.wb.hWnd,
			      htmurl,
			      xfer,
			      false,
			      width, height,
			      7,
			      dialog_title);
    
    if(ok == 1) // If "OK" button is pressed
    {
      MeshType = new Number(xfer("MeshType"));
      RefSize = new Number(xfer("RefSize"));
      MinMeshSize = new Number(xfer("MinMeshSize"));
      MaxMeshSize = new Number(xfer("MaxMeshSize"));
      NormalAngle = new Number(xfer("NormalAngle"));
      GrowthRate = new Number(xfer("GrowthRate"));
      Pinch = new Number(xfer("Pinch"));
      NbInflation = new Number(xfer("NbInflation"));
      VlayerSize = new Number(xfer("VlayerSize"));
      IbSize = new Number(xfer("IbSize"));
      IntfVlayerCh = new Number(xfer("IntfVlayerCh"));
      ChSize = new Number(xfer("ChSize"));
      ChGrowthRate = new Number(xfer("ChGrowthRate"));
      VT = new Number(xfer("VT"));
      AutoPinch = new Number(xfer("AutoPinch"));
      IntfCrevicePiston = new Number(xfer("IntfCrevicePiston"));
      CreviceNoOfLayers = new Number(xfer("CreviceNoOfLayers"));
      SparkSOI = new Number(xfer("SparkSOI"));
      SoiRadius = new Number(xfer("SoiRadius"));
      ChInflation = xfer("ChInflation");
      ICSetPanelSessionVarFromGlobalVars();
      ICWriteSettingsFileForAddin();
      IcSetMeshSettings();
   }
    else {// "Cancel" button is pressed
	/*g_oApplet.Script.WBScript.Out(
	    "You Pressed the CANCEL button",
	    true,
	    "Message");*/
	    }
}

function ICECreateWorksheet() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name, found,chNs=null,layer=null,piston=null;
  var j = 0;
  var partid, topid, pos;

  var nsl = branch.Components;
  var singleZoneTopo = IsSingleZoneTopo();
  var arrNs = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    var str1 = String(ns.Name);
    if (str1 == "fluid-ch")
      chNs = ns;
    else if (str1 == "fluid-layer-cylinder")
      layer = ns;
    else if (str1 == "fluid-piston")
      piston = ns;
    if(singleZoneTopo){
      if((str1.indexOf("fluid")==0)&&(str1.indexOf("-port")!=-1))
        arrNs.push(ns);
    }
  }

  if (chNs)
    arrNs.push(chNs);
  if (layer)
    arrNs.push(layer);
  if (piston)
    arrNs.push(piston);

  //IB-bottom bodies
  sm.Clear();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-ib") != -1)) {
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        var name = getBodyName(partid, topid);
        if (name.indexOf("-top") != -1)
          continue;
        sm.AddToSelection(partid, topid, false);
      }
    }
  }
  if(sm.SelectedCount){
    ns = ds.Script.addNamedSelection(false, "ib-worksheet", null);
    if (typeof (ns) != "undefined"){
      ns.SendToSolver = false;
      arrNs.push(ns);
    }
  }
  //Add worksheet item
  var meshGroup = branch.MeshControlGroup;
  for (var i = 0; i < arrNs.length; i++) {
    meshGroup.AddNamedSelectionList();
    var numCases = meshGroup.NumNamedSelectionEntries;
    meshGroup.WorkSheetNamedSelectionId(numCases - 1) = arrNs[i].ID;
    arrNs[i].WorksheetMeshing = true;
    meshGroup.MeshWorksheetNamedSelectionActive(numCases - 1) = 1;
  }
  
}
function doICEGenerateMesh() {
  try {
    IcGenerateMesh();
  }
  catch (error) {
    if (g_oApplet)
      g_oApplet.Script.WBScript.Out(error.description, true, error.name);
  }
}
function IcGenerateMesh() {
  var ns, name, found;
  var j = 0,i=0,k=0;
  var partid, topid, pos;
  var arr;
  arr = new Array();
  
  var MessageDatabase = ds.Tree.MessageDatabase;
  if (MessageDatabase)
    MessageDatabase.Clear();
 
  var branch = ds.Tree.FirstActiveBranch;
  ds.Script.changeActiveObject(branch.MeshControlGroup.Id);

  var solver = ICGetSessionVaribale("ICESolver");    
  if(solver=="Forte")
  {
    var protoGroup = ICGetProtoGroup();
    if (!protoGroup)
      return;
    childList = protoGroup.Children;
    if(childList.Count!=1)
      return;
    var proto = childList.item(1);
    childList = proto.Children;
    var portProto;
    for (i = 1; i <= childList.Count; i++) {
      proto = childList.item(i);
      var name = new String(proto.Name);
      if(name.indexOf("forte-sphere") != -1)
        proto.Suppressed = true;
      else
      {
        proto.Suppressed = false;
        portProto = proto;
      }
    }
    ICDoModelPreviewMesh();
    //if (portProto.Elements == 0) 
      //ICdoModelPreviewSurfaceMesh();
    var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
    if(meshGroup.State==ds.Script.id_Updated)
    {
      try
      {
        var surfaceMeshPath = ICGetSessionVaribale("ICEForteMeshFilePath");
        if(surfaceMeshPath!="")
        {
          var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject"); 
          if(fileSys.FileExists(surfaceMeshPath))
            fileSys.DeleteFile(surfaceMeshPath);
          meshGroup.WriteFluentInputFile(surfaceMeshPath);
          if(fileSys.FileExists(surfaceMeshPath))
            ICEAddMessage("Mesh file "+surfaceMeshPath+" has been successfully exported.","Info")
        }
      }
      catch(error)
      {
      }
    }
    return;
  }
  else if (IsPortFlow()) {
    GeneratePortFlowMesh();
    return;
  }
  else if(IsCombustion()){
    ICDoModelPreviewMesh();
    return;
  }
  else if(IsSingleZoneTopo()){
    ICDoModelPreviewMesh();
    ICMeshTheCreviceBody();
    return;
  }

  var nsl = branch.Components;
  count = 0;
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 8);
    if (str2.indexOf("fluid-ch") != -1) {
      arr.push(ns);
      break;
    }
  }
  sm.Clear();
  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      topid = str1.substring(pos + 1);
      sm.AddToSelection(partid, topid, false);
    }
  }
  if (sm.SelectedCount) {
    ICDoModelPreviewMeshBodySelection();
    sm.Clear();
  }
  if (CheckForTheErrorMessage("The meshing process was aborted as you requested."))
    return;
  checkIfHardEdgeSizingIsCausingIssue(); //aston martin Test 17 is failing with hard sizing
  
  // Iterative meshing for port bottom
  var meshGroup = branch.MeshControlGroup;
  meshGroup.MeshMetric = 7; //Set Skewness Mesh metric
  IterativelyMeshPortBottom();

  sm.Clear();
  ICDoModelPreviewMesh();
  if (CheckForTheErrorMessage("The meshing process was aborted as you requested."))
    return;

  sm.Clear();
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var childList = protoGroup.Children;
  ICMeshTheCreviceBody();

  //DE17827 Bosch marting engine fails because of automatic VC
  var needtoremesh = checkPortsIfAnyVCIsCausingError();
  if (needtoremesh)
    ICDoModelPreviewMesh();
  if (CheckForTheErrorMessage("The meshing process was aborted as you requested."))
    return;

  //For cummins case 7, body by body meshing succeeds.
  var portArr, bodyArr, otherPartArr, otherBodyArr;
  portArr = new Array();
  bodyArr = new Array();
  otherPartArr = new Array();
  otherBodyArr = new Array();
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;
    if (child.Elements > 0) 
      continue;
    var strName = String(child.Name);
    if ((strName.indexOf("-port") == -1)) {
      protoList = child.Prototypes;
      for (var k = 1; k <= protoList.Count; k++) {
        proto = protoList.item(k);
        bodies = proto.Part.BRep.Bodies;
        otherPartArr.push(proto.Part.Id);
        otherBodyArr.push(bodies.item(k).Id);
      }
      continue;
    }
    protoList = child.Prototypes;
    for (var k = 1; k <= protoList.Count; k++) {
      proto = protoList.item(k);
      strName = proto.Name;
      bodies = proto.Part.BRep.Bodies;
      if ((strName.indexOf("Port") == 0)) {
        portArr.push(proto.Part.Id);
        bodyArr.push(bodies.item(k).Id);
        continue;
      }
      sm.AddToSelection(proto.Part.Id, bodies.item(k).Id, false);
    }        
  }
  if (sm.SelectedCount) {
    ICDoModelPreviewMeshBodySelection();
    sm.Clear();
    if (portArr.length) {
      for (k = 0; k < portArr.length; ++k)
        sm.AddToSelection(portArr[k], bodyArr[k], false);
      ICDoModelPreviewMeshBodySelection();
      sm.Clear();
    }
  }
  if(otherPartArr.length){
    for(k=0;k<otherPartArr.length;++k)
      sm.AddToSelection(otherPartArr[k], otherBodyArr[k], false);
    ICDoModelPreviewMeshBodySelection();
    sm.Clear();
  }
  if (CheckForTheErrorMessage("The meshing process was aborted as you requested."))
    return;

  //Suppress the Sweep controls , for Bosch Padmesh geometry.
  SuppressSweepMethods();

  //DE17827 Bosch marting engine fails because of automatic VC
  var needtoremesh = checkPortsIfAnyVCIsCausingError();
  if (needtoremesh)
    ICDoModelPreviewMesh();

  /*ds.Script.changeActiveObject(branch.ContactGroup.Id);
  ds.Script.doAutoConnectionsGeneration();*/

  CheckIfAllTheFacesAreThereInNS();

  DisplaySkewnessWarning();
}
function ICMeshTheCreviceBody()
{
  var branch = ds.Tree.FirstActiveBranch;
  if(!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var childList = protoGroup.Children;
  sm.Clear();  
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    var notMeshed = false;
    if (ds.Script.id_BodyGroup != child.Class) continue;
	
    var strName = String(child.Name);
    if ((strName.indexOf("crevice") == -1))
      continue;  
	//check if any of the bodies in crevice has 0 mesh count
    protoList = child.Prototypes;
	  for (var k = 1; k <= protoList.Count; k++) {
	      proto = protoList.item(k);
	      if (proto.Elements == 0)
	        notMeshed = true;
	  }  
    if (notMeshed) {
      for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        str1 = new String(meshctrl.Name);
        if ((str1.indexOf("crevice") == -1))
          continue;
        if (meshctrl.ControlType == ds.Script.id_BodyMeshType) {
         meshctrl.SubValue = false;     //suppress thinsweep
          protoList = child.Prototypes;
          for (var k = 1; k <= protoList.Count; k++) {
            proto = protoList.item(k);
            bodies = proto.Part.BRep.Bodies;
            sm.AddToSelection(proto.Part.Id, bodies.item(k).Id, false);          
          }    
        }
      }
    }
  }
  if (sm.SelectedCount) {
    ICDoModelPreviewMeshBodySelection();
    sm.Clear();
  }
}
function ICdoModelPreviewSurfaceMesh()
{
  if (typeof (ds.Script.lv) != "undefined")	  
    ds.Script.doModelPreviewSurfaceMesh();
  else
	  ICReallydoPreviewMesh( 0 );
}
function ICDoModelPreviewMesh()
{
  if (typeof (ds.Script.lv) != "undefined")	  
    ds.Script.doModelPreviewMesh();
  else
    ICReallydoPreviewMesh( 1 );
}
function ICDoModelPreviewMeshBodySelection()
{
  if (typeof (ds.Script.lv) != "undefined")	  
    ds.Script.doModelPreviewMeshBodySelection();
  else
  	ICReallydoPreviewMesh( -1 );
}
//This function is an exact copy of reallydoPreviewMesh() of DSMenuScript.js. Then removed graphics calls to work in batch mode. Also removed progress bar display.
function ICReallydoPreviewMesh(iAlgorithm, workFlow) {
  var branch = ds.Tree.FirstActiveBranch;

    var FuncFrmSol = false; // This is a flag that determines if the function reallydoPreviewMesh is called from inside the function doSolutionFindAnswers ... i.e. to distinguish a specific workflow
    if (workFlow == true)   // This code was added to rectify defect DE72025
        FuncFrmSol = true;
    
    var meshGroup;
	var bFromSm = false;
	var bMeshPart = false;
	var bFromWorkSheet = false;
	var bDoPreview = false;
	
	if ( -1 == iAlgorithm )
	{
		iAlgorithm = 1;
		bFromSm = true;
	}
	else if ( -3 == iAlgorithm )
	{
		iAlgorithm = 0;
		bFromSm = true;
	}
    else if ( -4 == iAlgorithm )
	{
		iAlgorithm = 1;
		bFromSm = true;
		bMeshPart = true;
	}
	else if ( -5 == iAlgorithm )
	{
		iAlgorithm = 0;
		bFromSm = true;
		bMeshPart = true;
	}
	else if(4 == iAlgorithm || 2 == iAlgorithm)  
	    bDoPreview = true;
	
	// if a prototype or bodygroup, just mesh the selected.  otherwise,do everything
	if( branch  )
	{
		meshGroup = branch.MeshControlGroup;
	    var isCutcellMesh = meshGroup.AssemblyMeshingMethod;
	    
	    //ignore worksheet for tree selection
	    var bFromTreeSelection = false;
	    if(ds.Tree.ActiveObjects)
	    {
	       var selobj = ds.Tree.ActiveObjects(1);
	       if ((selobj.Class == ds.Script.id_Prototype || selobj.Class == ds.Script.id_BodyGroup) && !FuncFrmSol)   // flag "FuncFrmSol" was added to rectify defect DE72025
			 bFromTreeSelection = true;	   
	    }
	    
	    //decide if use mesh worksheet sequence
	    if(meshGroup.NumNamedSelectionEntries > 0 && !meshGroup.DirectMeshingRecording)
	    {
	        if(isCutcellMesh == 0 && iAlgorithm != 0 && !bFromSm && !bFromTreeSelection && !bDoPreview )  
	        {
	           bFromWorkSheet = true; 
	           iAlgorithm = 6;
	        }
        } 
		
		if( meshGroup )
		{
		    
			meshGroup.ClearMeshQueue();
			if ( bFromSm  )
			{
				var protoGroup = branch.PrototypeGroup;

				var selectedParts = null;

				selectedParts = protoGroup.GetSelectedPrototypes(sm);

				var numSel = selectedParts.Count;

				var i=1;

				//ds.Script.stateEngineObject.Silent = true;
				ds.EnableRefreshParameters = false;
				ds.Script.bNotFromDetail = true;
				var PartToMesh;
				for(i=1; i<=numSel; i++)
				{
					var selItem  = selectedParts.Item(i);

					if(!selItem)
						continue;
						
                    if(bMeshPart)
                    {
                       if(selItem.Class  == ds.Script.id_Prototype)
                       {
                            var PartToMesh = selItem.parent;
                            if(!PartToMesh)
                               meshGroup.AddPartToMeshQueue( selItem.ID );
                            else
                            {
                                  var bodyList = PartToMesh.Children;
                                  var j ;
                                  for(j = 1; j<=bodyList.Count; j++)
                                  {
                                     var proto = bodyList.Item(j);
		                             meshGroup.AddPartToMeshQueue( proto.ID );
                                  }
                            }
                       }
                    }
					else
					  meshGroup.AddPartToMeshQueue( selItem.ID );
				}
			}
			else if(ds.Tree.ActiveObjects && iAlgorithm != 2 && iAlgorithm != 6)
			{
			    
				var iNumObjects = ds.Tree.ActiveObjects.Count;
				for( var i=1; i<=iNumObjects; i++ )
				{
					var obj = ds.Tree.ActiveObjects(i);

					if ((obj.Class != ds.Script.id_Prototype && obj.Class != ds.Script.id_BodyGroup) || FuncFrmSol) // flag "FuncFrmSol" was added to rectify defect DE72025
					{
						meshGroup.AddPartToMeshQueue( -1 ); // signify we will mesh everything
						break;
				    }
					else
						meshGroup.AddPartToMeshQueue( obj.ID );
				}
			}
		}
	}

	sm.Clear();

    if ( ds.Script.lv )
	    lvFroceOutOfEdit();

	if( meshGroup )
	{
	   
        var partCount = 0;

		if( branch.Prototypes )
      		partCount = branch.Prototypes.Count;
		if (partCount == 0)                   // if no geometry return
		    return;
		try
		{
           
            // create the progress pane
            var progressObj = ds.Script.CreateActiveXObject(ds.Script.GenWBProgId("AnsCoreObjects.AnsProgress"));
            //progressStatusPaneStart(localString("ID_DSPreviewMeshStatus"), progressObj, false, true, "progress.htm");
	        var meshstate = ds.Script.stateEngineObject.ObjectState(meshGroup.Id);
            if ( meshstate != ds.Script.id_Updated )
            {
			    if ( 0 == iAlgorithm )
				    meshGroup.SurfaceMeshParts(progressObj);
			    else if ( 1 == iAlgorithm )
				    meshGroup.MeshParts(progressObj,0);
			    else if ( 2 == iAlgorithm )
				    meshGroup.PreviewMeshControls(1,0,progressObj);
				  else if ( 4 == iAlgorithm )
				    meshGroup.PreviewInflation(progressObj);
			    else if(  6 == iAlgorithm )
				    meshGroup.MeshWorksheetGenerateMesh(progressObj);
          else if( 7 == iAlgorithm )
            meshGroup.WrapMeshParts(progressObj);
			}

			if( true == meshGroup.MeshingFailed )
			{			   
			    ds.Script.addProblematicNamedSelections();
			    meshGroup.DrawProblematicGeometry();
			    ds.Script.changeActiveObject( meshGroup.ID );
			}
			//progressStatusPaneFinish();

            // update the tree icons
            ds.Script.updateNodeState( meshGroup.ID, false );

			ds.Script.disableTabs(false);

            // give the user a message if something failed
            ds.Script.handleErrorState();
		}
		catch(error)
		{
			ds.Script.disableTabs(false);
			//progressStatusPaneFinish();
            ds.Script.updateNodeState( meshGroup.ID, false );
            ds.Script.handleErrorState();

			return 0;
		}
	}
	// don't force selection of mesh group after meshing. dah, 2/27/02
	//changeActiveObject( meshGroup.ID );
	//ds.Graphics.Draw2(ds.Tree.FirstActiveObjectID);
	if ( ds.Script.lv )
        ds.Script.lvUpdateProps();
}
function getFluentOldApproach() {
  var str1, i, j, str2;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var Parts = Assy.Parts(true);
  var k, Part;
  var oldApproach = 0;

  for (k = 1; k <= Parts.Count; ++k) {
    Part = Parts.Item(k);
    str1 = String(Part.Name);
    var attrs = Part.AttributesByName(1,"ICEngine_FluentOldApproach");
    for (j = 1; j <= attrs.Count; ++j) {
      var attr = attrs.item(j);
      if (attr.Type == 4) {
        if (attr.Boolean)
          oldApproach = 1;
      }
      else {
        if (attr.Value)
          oldApproach = 1;
      }
      break;
    }
  }
  return oldApproach;
}
function getMeshSize() {
  var str1, i, j, str2;
  var meshSize = 0.93;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var Parts = Assy.Parts(true);
  var k, Part;

  var attrs = Assy.AttributesByName(1,"ICEngine_MeshSize");
  if (attrs.Count) {
    for (j = 1; j <= attrs.Count; ++j) {
      var attr = attrs.item(j);
      meshSize = attr.Double;
      break;
    }
    return meshSize;
  }
  
  for (k = 1; k <= Parts.Count; ++k) {
    Part = Parts.Item(k);
    str1 = String(Part.Name);
    var attrs = Part.AttributesByName(1,"ICEngine_MeshSize");
    for (j = 1; j <= attrs.Count; ++j) {
      var attr = attrs.item(j);
      meshSize = attr.Double;
      break;
    }
  }
  return meshSize;
}
function getCreviceThickness() {
    var str1, i, j, str2;
    var thickness = 1;
    var Assys = pm.assemblies;
    var Assy = Assys.Item(1);
    var Parts = Assy.Parts(true);
    var k, Part;

    var attrs = Assy.AttributesByName(1,"ICEngine_Crevice_Thickness");
    if (attrs.Count) {
        for (j = 1; j <= attrs.Count; ++j) {
            var attr = attrs.item(j);
            thickness = attr.Double;
            break;
        }
        return thickness;
    }

    for (k = 1; k <= Parts.Count; ++k) {
        Part = Parts.Item(k);
        str1 = String(Part.Name);
        var attrs = Part.AttributesByName(1,"ICEngine_Crevice_Thickness");
        for (j = 1; j <= attrs.Count; ++j) {
            var attr = attrs.item(j);
            thickness = attr.Double;
            break;
        }
    }
    return thickness;
}
function IsNew() {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl, str1;
  var j;

  var solver = ICGetSessionVaribale("ICESolver");
  if(solver=="Forte"){
    var setupAlreadyDone = ICGetSessionVaribale("ICEForteSetupDone");
    if(setupAlreadyDone=="true")
      return false;
    return true;
  }

  for (j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    str1 = new String(meshctrl.Name);
    if ((str1.indexOf("(ib)") != -1)||(str1.indexOf("(ch)") != -1))
      break;
  }
  if (j > mehctrls.Count) {
    return true;
  }
  else {
    return false;
  }
}
function IcSetMeshSettings() {
  var j;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl,str1;
  if (IsNew()) {
    doAutomateICEMeshing();
  }
  else {//Edit the existing mesh controls
    //Set the units to mm
    //ds.Script.doUnitsMenu(2);
    ds.UnitSystemID = 2;
    
    var minLift = 0.2;
    var attrValue = getMinLift();
    if (attrValue > 0)
      minLift = attrValue;

    var meshSize = getMeshSize();
    meshGroup.MaxFaceElementSize = MaxMeshSize/*3 * meshSize*/;
    meshGroup.MaxSizeSF = MaxMeshSize/*3 * meshSize;*/ ;
    meshGroup.MinSizeSF = MinMeshSize/*meshSize / 2*/;
    meshGroup.SpanningAngleSF = NormalAngle/*30*/;
    meshGroup.TransitionSF = GrowthRate;
    if(NbInflation > 0)
      meshGroup.FirstLayerHeight = meshSize / (2*NbInflation)/*5*/;
    else
      meshGroup.FirstLayerHeight = meshSize / 5;
    meshGroup.NumLayers = NbInflation/*5*/;
    meshGroup.PinchTolerance = Pinch/*0.1*//*meshSize / 10*/;
    if(AutoPinch==1){
      meshGroup.PinchGenerateOnRefresh = 1;
    }
    else{
      meshGroup.PinchGenerateOnRefresh = 0;
    }

    var IsRegen=0;
    ICDefineIBMesh(IsRegen);
    ICDefineVlayerMesh(IsRegen);

    //Ch
    for (j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      str1 = new String(meshctrl.Name);
      if ((str1.indexOf("port") != -1)) 
        break;
      if ((str1.indexOf("(intf-ch-upper)") != -1) || (str1.indexOf("(intf-ch-lower)") != -1)) {
        if (meshctrl.ControlType == ds.Script.id_Size) {
          meshctrl.ESize = IntfVlayerCh;
        }
      }
      else if (str1.indexOf("valves-bottom") != -1) {
        meshctrl.ESize = round(ChSize * 1./3.);
      }
      else if ((str1.indexOf("(ch)") != -1)) {
        if (meshctrl.ControlType == ds.Script.id_Size) {
          meshctrl.ESize = ChSize;
          meshctrl.SizingTransition = ChGrowthRate;
        }
      }
      else if ((str1.indexOf("(layer-cylinder)") != -1)) {
        if (meshctrl.ControlType == ds.Script.id_BodyMeshType)
          meshctrl.ESize = ChSize;
        if (meshctrl.ControlType == ds.Script.id_Size) {
          meshctrl.ESize = ChSize;
          meshctrl.SizingTransition = ChGrowthRate;
        }
      }
      else if ((str1.indexOf("(piston)") != -1)) {
        if (meshctrl.ControlType == ds.Script.id_Size)
          meshctrl.ESize = ChSize * 1.0;
      }
      else if ((str1.indexOf("(ch lower,upper,valve)") != -1)||
               (str1.indexOf("(intf-piston-ch)") != -1)||
               (str1.indexOf("(ch-sweep-source)") != -1)) {
        if (meshctrl.ControlType == ds.Script.id_Size)
          meshctrl.ESize = ChSize;
      }
    }
    //Port
    for (j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      str1 = new String(meshctrl.Name);
      if ((str1.indexOf("port") == -1))
        continue;
      if (meshctrl.ControlType == ds.Script.id_Inflation){
        meshctrl.NumLayers = NbInflation;
        if(NbInflation > 0)
          meshctrl.FirstLayerHeight = meshSize / (2*NbInflation);
        else
          meshctrl.FirstLayerHeight = meshSize / 5;
      }
      else if (meshctrl.ControlType == ds.Script.id_Size){
        if ((str1.indexOf("-ibVlayer") != -1))
          meshctrl.ESize = VlayerSize;
        else if(meshctrl.SubType == 0)
          meshctrl.ESize = VlayerSize/2.0;
        else
          meshctrl.NDiv=NbInflation;
      }
    }
    if(AutoPinch==0)
      ICDeleteAutomaticPinchControls();
    else
      ICECreatePinch();
    ICEDefineSparkBOIMesh(0);
    

    // define face sizing near valve seat
    if(IsSingleZoneTopo()){
      ICDefineValveSeatFaceSizing();
      ICDefineSingleZoneInflation(0);
    }
    else{
      ICEDefineChamberInflation(0);
    }
    //Crevice Mesh
    //==================================
    ICDefineFaceSizingCylCrevice();
    ICDefineCreviceThinSweepMesh();
    ICDefineFaceSizingCreviceInterface();
  }
  //Suppress ch refinement if port are not present
  if(DoesItContainPorts()==0)
  {
    var mehctrls = meshGroup.MeshControls;
    for (j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      str1 = new String(meshctrl.Name);
      if (/*(str1.indexOf("(intf-vlayer-ch)") != -1)||*/
          (str1.indexOf("(intf-ch-vlayer-top-edges)") != -1)||
          (str1.indexOf("(valves-bottom)") != -1))
        meshctrl.SubValue=false;
    }      
  }
  //Set port flow session variable
  var coldflowsessionvarregen = getValveLiftsAttributeString();
  ICSetSessionVaribale("ICEngineValveLifts", coldflowsessionvarregen);

  CreateSectionPlanes();
  CreateViews();
  DeleteContacts();
}
// function to automate ICEngine meshing
function doAutomateICEMeshing() {
  if (typeof (ds.Script.lv) != "undefined")
    ds.Script.lvFroceOutOfEdit();
  
  var branch = ds.Tree.FirstActiveBranch;
  if (branch) {
    var meshGroup = branch.MeshControlGroup;
    if (meshGroup) {
      var partCount = 0;
      if (branch.Prototypes)
        partCount = branch.Prototypes.Count;
      if (partCount == 0)                   // if no geometry return
        return;

      ICECreateWorksheet();
      
      //Set the units to mm
      //ds.Script.doUnitsMenu(2);
      ds.UnitSystemID = 2;

      // Finding the mesh size
      //=============================
      var meshSize = getMeshSize();
      var oldApproach = getFluentOldApproach();


      // Meshing Options
      //=============================
      meshGroup.PhysicsPreference = 2;
      meshGroup.SolverPreference = 0;
      meshGroup.AdvancedSizeFunction = 2;
      //meshGroup.ElementSize//internally its face size
      meshGroup.MaxFaceElementSize = MaxMeshSize/*3 * meshSize*/;
      meshGroup.MaxSizeSF = MaxMeshSize/*3 * meshSize;*/ ;
      meshGroup.MinSizeSF = MinMeshSize/*meshSize / 2*/;
      meshGroup.MeshDefeatureTol = MinMeshSize/2.0;
      meshGroup.SmoothingOption = 2;
      meshGroup.SpanningAngleSF = NormalAngle/*30*/;
      meshGroup.TransitionSF = GrowthRate;

      meshGroup.InflationMaximumAngle = 160;
      var singleZoneTopo = IsSingleZoneTopo();
      if(!singleZoneTopo){
        meshGroup.InflationOption = 4;
        if(NbInflation > 0)
          meshGroup.FirstLayerHeight = meshSize / (2*NbInflation)/*5*/;
        else
          meshGroup.FirstLayerHeight = meshSize / 5;
        meshGroup.LastAspectRatio = 5;
        meshGroup.InflationMaximumAngle = 180;
      }
      meshGroup.NumLayers = NbInflation/*5*/;
      meshGroup.AdvancedInflationOptions = true;
      meshGroup.CollisionAvoidance = 1; //1-Compression, 2-stair stepping.

      meshGroup.PinchTolerance = Pinch/*0.1*//*meshSize / 10*/;
      if(AutoPinch==1){
        meshGroup.PinchGenerateOnRefresh = 1;
      }
      else{
        meshGroup.PinchGenerateOnRefresh = 0;
      }

      suppressExistingControls();

      var hideStates=new Array();
      var suppressStates=new Array();
      IceStoreTheOriginalHideSuppressStates(hideStates,suppressStates);
      //ds.Script.doUnSuppressAllParts();
      
      //create virtual cells
      //VT: 0-Low, 1-Medium, 2-High, 3-None
      var beta = 1;
      if(g_oApplet){
        beta = g_oApplet.Script.wb.PreferenceMgr.Preference("PID_Show_Beta_Options");
      }
      beta=1;//This feature is not beta
      if(beta==1){
        ICStoreNsFacesBeta();
      }
      var createVCforAllBodies=0;
      if(VT != 3)
        ICECreateAutomaticVC(createVCforAllBodies);
     //Hiding all bodies improves the performance of project to underlying geomtry for vc
      IceHideAllParts();
      //Just show ch and hide ports, so that floodselect will only work on ch as intended
      IceShowBodyByName("ch");
      ICECreateVCforDomeSliverFaces(false);
      IceHideAllParts();
     //port bottom bodies should be visible otherwise floodselect wont work
      IceShowPortBottom();
      ICECreateVCPortBottom();
      ICECreateVCPortBottomThinFaces();
      if(beta==1){
        ICUpdateNSWithVCBeta();
      }
      else{
        ICUpdateNSWithVC();
      }
      ICECreateVirtualFaces();
      ICECreateVirtualFacesForVlyer();
      //VCProjectToGeometry = 0;
      ICECreateVirtualEdges(0,0); //for Vlayer and IB
      //VCProjectToGeometry = 1;
      ICProjectToUnderlyingGeomVC();
      IceShowAllParts();
      // IB Meshing
      //=============================
      var IsRegen=0;
      ICDefineIBMesh(IsRegen);

      // OB + V-layer meshing:
      //=============================
      ICDefineVlayerMesh(IsRegen);

      // Chamber Meshing
      //=============================
      ICDefineChamberMesh(meshSize);
      ICDefineStraightValveChamberMesh(meshSize);
      ICEAddSparkCoordinateSystems();
      ICEDefineSparkBOIMesh(0);

      // define face sizing near valve seat
      if(singleZoneTopo){
        ICDefineValveSeatFaceSizing();
        ICDefineSingleZoneInflation(0);
      }
      else{
        ICEDefineChamberInflation(0);
      }

      // Port Meshing
      //=============================
      ICDefinePortMesh(meshSize, oldApproach);

      //Crevice Mesh
      //==================================
      ICDefineFaceSizingCylCrevice();
      ICDefineCreviceThinSweepMesh();
      ICDefineFaceSizingCreviceInterface();
     
      // Create pintch
      if(AutoPinch==1){
        ICECreatePinch();
      }

      //Remove ice-user-* named selection faces from default NS
      RemoveUserNSfromDefaultNS();
      
      //ds.Script.endWaitCursor();

      CheckIfAllTheFacesAreThereInNS();
      IceRestoreTheOriginalHideSuppressStates(hideStates,suppressStates);
    }
  }
}
function ICDefineVlayerMesh(IsRegen) {
  var i, j, k, l, str1;
  var nsl, ns;
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var found;
  var Assys, Assy;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);
  var meshSize = getMeshSize();
  var oldApproach = getFluentOldApproach();

  // OB + V-layer meshing:
  //=============================
  var valveLifts = getValveLifts();
  var refMeshSize = getPanelRefSize();
  refMeshSize = Math.round(refMeshSize * 100);
  refMeshSize = refMeshSize / 100;
  var vlayerHeight = refMeshSize * 0.4;

  sm.Clear();

  var Parts = Assy.Parts(true);
  var k, Part, partArr, topoArr;
  partArr = new Array();
  topoArr = new Array();

  for (k = 1; k <= Parts.Count; ++k) {
    Part = Parts.Item(k);
    str1 = String(Part.Name);
    var pos = str1.indexOf("-vlayer");
    if (pos== -1)
      continue;
    sm.Clear();
    var attrs = Part.AttributesByName(1,"ICEngine_VlayerEdge");
    for (j = 1; j <= attrs.Count; ++j) {
      var attr = attrs.item(j);
      var partid = Part.Id;
      var topid = attr.TopoId;
      sm.AddToSelection(partid, topid, false);
      topoArr.push(topid);
      partArr.push(partid);
    }
    if (sm.SelectedCount == 0)
      continue;
    var vlayerName=str1;
    str1 = str1.substring(0, pos);
    var lift = 0.;
    for (j = 0; j < valveLifts.length; j++) {
      if (valveLifts[j] == str1) {
        lift = valveLifts[j + 1];
        break;
      }
      j++;
    }
    var nbDiv = Math.round(lift / vlayerHeight);
    if (oldApproach) {
      if (nbDiv < 1)
        nbDiv = 1; // Nb divisions
    }
    else {
      if (nbDiv < 4)
        nbDiv = 4;  // Nb divisions
    }
    var ctrlName = "(" + vlayerName + "-nbLayers)";
    var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_Size);
    //Edge sizing
    if(!MeshCtrlObj){
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      MeshCtrlObj.SubType = 1; // Nb divisions
      MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " " + ctrlName;
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
    else{
      if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
      {
        ctrlName = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
      }
    }
    MeshCtrlObj.NDiv = nbDiv; // Nb divisions
  }

  var arr = new Array();
  count = 0;
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-vlayer") != -1)) {
      arr[count] = ns;
      ++count;
    }
  }
  sm.Clear();
  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      var pos = str1.indexOf(";");
      var partid = str1.substring(0, pos);
      var topid = str1.substring(pos + 1);
      sm.AddToSelection(partid, topid, false);
    }
  }
  if (!arr.length) return;
  var ctrlName = "(vlayer)";
  var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_Size);
  //Body sizing
  if (!MeshCtrlObj) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
    MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
    MeshCtrlObj.Name = MeshCtrlObj.Name + " (vlayer)";
    ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
  }
  else{
    if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
    {
      ctrlName = MeshCtrlObj.Name;
      MeshCtrlObj.GeometrySelection = sm;
      MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
    }
  }
  if(!IsRegen)
    MeshCtrlObj.ESize = VlayerSize;
    
  //Sweep method
  for (j = 0; j < arr.length; j++) {
    sm.Clear();
    ns = arr[j];
    partid = "";
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      var topid = str1.substring(pos + 1);
      sm.AddToSelection(partid, topid, false);
    }
    if (partid == "") continue;
    var partIdInt = parseInt(partid);
    var part = Assy.PartById(partIdInt);
    var attrs = part.AttributesByName(1,"ICEngine_SweepSources");
    var attr;

    var sourceArr;
    sourceArr = new Array();
    for (i = 1; i <= attrs.Count; ++i) {
      attr = attrs.item(i);
      sourceArr.push(attr.TopoId);
    }

    var bottomfaceArr = new Array();
    for (k = 1; k <= nsl.Count; ++k) {
      ns = nsl.item(k);
      str1 = String(ns.Name);
      str2 = str1.substring(str1.length - 4, str1.length);
      if (str2.indexOf("-ob") == -1)
        continue;

      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        if (partIdInt != partid)
          break;
        var topid = str1.substring(pos + 1);
        bottomfaceArr.push(parseInt(topid));
      }
      if (bottomfaceArr.length)
        break;
    }

    var vlayerName=String(arr[j].Name);;
    vlayerName = vlayerName.substring(6, vlayerName.length); //remove fluid-
    var ctrlName = "("+vlayerName+")";
    var MeshCtrlObj1 = ICGetMeshControlByName(ctrlName,ds.Script.id_BodyMeshType);
    //Sweep method
    if(!MeshCtrlObj1){
      MeshCtrlObj1 = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
      MeshCtrlObj1.Value = 5;
      MeshCtrlObj1.SourceTargetSelection = 1;
      MeshCtrlObj1.SweepESizeType = 1;
      MeshCtrlObj1.SweepShape = 2;
      MeshCtrlObj1.SweepBiasType = 3;
      MeshCtrlObj1.SweepBiasValue = 1.0;
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj1.Name = MeshCtrlObj1.Name + " (" + vlayerName + ")";
      ds.Script.addNodeAndChildren(MeshCtrlObj1, MeshCtrlGrpNode);
    }
    else{
      if (MeshCtrlObj1.GeometryNum != sm.SelectedCount)
      {
        ctrlName = MeshCtrlObj1.Name;
        MeshCtrlObj1.GeometrySelection = sm;
        MeshCtrlObj1.Name = ctrlName; //Name is getting lost after setting supports.
      }
    }
    //Source geometry
    sm.Clear();
    for (i = 0; i < bottomfaceArr.length; ++i) {
      sm.AddToSelection(partIdInt, bottomfaceArr[i], false);
    }
    MeshCtrlObj1.SourceGeometry = sm;

    // Sizing for source and target face edges
    sm.Clear();
    var faces, face, bodies, bodies1, size, edges, id;
    size = sourceArr.length;
    var sourceArrCal =  new Array();
    for (i = 0; i < size; ++i) {
      face = part.BRep.Cell(sourceArr[i]);
      bodies = face.Bodies;
      if (bodies.Count != 2) continue;
      faces = bodies.item(1).Faces;
      for (k = 1; k <= faces.Count; ++k) {
        face = faces.item(k);
        if (sourceArr[i] == face.Id) continue;
        bodies1 = face.Bodies;
        if (bodies1.Count != 2) continue;
        if (((bodies.item(1).Id == bodies1.item(1).Id) && (bodies.item(2).Id == bodies1.item(2).Id))
              || ((bodies.item(2).Id == bodies1.item(1).Id) && (bodies.item(1).Id == bodies1.item(2).Id))) {
          sourceArrCal.push(face.Id);
        }
      }
      //Break even if other side of one source face is not found
      if(sourceArrCal.length==0)
        break;
    }
    sourceArr = sourceArr.concat(sourceArrCal);

    ICCreateEdgeSizingForVlayer(vlayerName,sourceArr,IsRegen);

    //Hard Edge sizing for circular edges

    var sourceEdgeArr = new Array();
    for (i = 0; i < sourceArr.length; ++i) {
      face = part.BRep.Cell(sourceArr[i]);
      edges = face.Edges;
      for (k = 1; k <= edges.Count; ++k)
        sourceEdgeArr.push(edges.item(k).Id);
    }

    sm.Clear();
    var allEdges = part.BRep.Cells(1);
    for (k = 1; k <= allEdges.Count; ++k) {
      id = allEdges.item(k).Id;
      for (i = 0; i < sourceEdgeArr.length; ++i) {
        if (id == sourceEdgeArr[i])
          break;
      }
      if (i == sourceEdgeArr.length)//not found
        sm.AddToSelection(partIdInt, id, false);
    }
    if (sm.SelectedCount) {
      var ctrlName = "("+vlayerName+"-cir)";
      var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_Size);
      if(!MeshCtrlObj){
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
        MeshCtrlObj.SubType = 1; // Nb divisions
        MeshCtrlObj.SizingType = 1; //Hard
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + vlayerName + "-cir)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
      else{
        if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
        {
          ctrlName = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
        }
      }
      if(!IsRegen){
        //Splitting vlayer with two plane, i.e 90deg sector for better mesh
        if(IsVlayerTwoPlaneSliceApproach())
          MeshCtrlObj.NDiv = (50*refMeshSize/VlayerSize)/2/*75*/; // Nb divisions
        else
          MeshCtrlObj.NDiv = (100*refMeshSize/VlayerSize)/2/*75*/; // Nb divisions
      }
    }
  }

}
function ICCreateEdgeSizingForVlayer(vlayerName,sourceArr,IsRegen){
  var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  var Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  var Assy = Assys.Item(1);
  
  var Parts = Assy.Parts(true);
  var found=false;
  var part;
  for (var k = 1; k <= Parts.Count; ++k) {
    part = Parts.Item(k);
    var str1 = String(part.Name);
    if (str1.indexOf(vlayerName) != -1){
      found=true;
      break;
    }
  }
  if(!found) return;
  var partIdInt=part.Id;
  var attrs = part.AttributesByName(1,"ICEngine_VlayerEdge");
  var partArr = new Array();
  var topoArr = new Array();
  for (j = 1; j <= attrs.Count; ++j) {
    var attr = attrs.item(j);
    var partid = part.Id;
    var topid = attr.TopoId;
    topoArr.push(topid);
    partArr.push(partid);
  }
  var pos = vlayerName.indexOf("-");
  if(pos==-1) return;
  var valveID = vlayerName.substring(0,pos);
  var intfNs = valveID+"-seat";
  var nsTopoArr=new Array(),nsPartArr=new Array();
  ICGetNSSupports("",intfNs,nsTopoArr,nsPartArr);
  if(nsPartArr.length==0) return;
  if(nsPartArr[0] != partIdInt) return;
  //Find the bodies attached to valveID-seat NS
  var intfBodiesArr=new Array();
  for (var i = 0; i < nsTopoArr.length; ++i) {
    var face = part.BRep.Cell(nsTopoArr[i]);
    var bodies = face.Bodies;
    if(bodies.Count==0)
      continue;
    intfBodiesArr.push(bodies.Item(1).Id);
  }
  var nbDivEdgeArr = new Array();
  var nbDivArr = new Array();
  var nbDivEdgeFaceAreaArr = new Array();
  var nbDivEdgeFaceAreaIndexArr = new Array();
  var NbDivisons=2;
  var SizingEdgeArr = new Array();
  for (var i = 0; i < sourceArr.length; ++i) {
    var face = part.BRep.Cell(sourceArr[i]);
    var edges = face.Edges;
    var bodies = face.Bodies;
    var IsIntfBody=false;
    if(FindInArray(intfBodiesArr,bodies.Item(1).Id) > -1)
      IsIntfBody=true;
    var SrcEdgeArr = new Array();
    for (var k = 1; k <= edges.Count; ++k) {
      var id = edges.item(k).Id;
      for (var l = 0; l < topoArr.length; ++l) {
        if (partArr[l] != partIdInt) continue;
        if (id == topoArr[l])
          break;
      }
      if (l == topoArr.length) {
        SrcEdgeArr.push(edges.item(k));
      }
    }
    if (SrcEdgeArr.length) {
      if ((SrcEdgeArr.length != 2)||(!IsIntfBody)) {
        SizingEdgeArr = SizingEdgeArr.concat(SrcEdgeArr);
      }
      else {//OB edges are of differnt legth so we have to give nb divisions instead of sizing, otherwise sweep will fail
        if((!IsRegen) && (VlayerSize > 0)){
          var Nb = Math.round((Math.max(IcGetEdgeLengthAMPUnits(SrcEdgeArr[0].Id, partIdInt), IcGetEdgeLengthAMPUnits(SrcEdgeArr[1].Id, partIdInt))) / (VlayerSize * 2. / 3.));
          if (Nb < 2) // ensure minimum two layers in the seat.
            Nb = 2;
          if(NbDivisons != Nb)
            NbDivisons = Nb;
        }
        nbDivEdgeArr = nbDivEdgeArr.concat(SrcEdgeArr);
        var area = IcGetSurfaceAreaAMPUnits(face.Id,partIdInt);
        var areaIndex = FindDoubleInArray(nbDivEdgeFaceAreaArr,area,2);
        if(areaIndex==-1)
        {
          areaIndex=nbDivEdgeFaceAreaArr.length;
          nbDivEdgeFaceAreaArr.push(area);
        }
        nbDivEdgeFaceAreaIndexArr.push(areaIndex);
        nbDivArr.push(NbDivisons);
      }
    }
  }
  //IcAreDoublesEqual
  //FindDoubleInArray
  var areaArr = new Array();
  areaArr = areaArr.concat(nbDivEdgeFaceAreaArr);
  sortInputArray(areaArr);
  var meshCtrlOrderArr = new Array();
  for(var k=0; k < areaArr.length; ++k){
    meshCtrlOrderArr.push(FindDoubleInArray(nbDivEdgeFaceAreaArr,areaArr[k],2));
  }
  for(var k=0; k < meshCtrlOrderArr.length; ++k)
  {
    sm.Clear();
    for (var j = 0; j < nbDivEdgeFaceAreaIndexArr.length; ++j) {
      if(nbDivEdgeFaceAreaIndexArr[j] != meshCtrlOrderArr[k])
        continue;
      NbDivisons = nbDivArr[j];
      for (var i = 2*j; (i < nbDivEdgeArr.length)&&(i < (2*j+2)); ++i) {
        sm.AddToSelection(partIdInt, nbDivEdgeArr[i].Id, false);
      }
    }
    if(sm.SelectedCount==0)
      continue;
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    var cntlName = vlayerName + "-nbdiv"+(k+1);
    for (var j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      if (meshctrl.ControlType != ds.Script.id_Size)
          continue;
      var str = new String(meshctrl.Name);
      if (str.indexOf(cntlName) == -1) continue;
      MeshCtrlObj = meshctrl;
    }
    if(!MeshCtrlObj){
      if(!IsRegen){
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
          MeshCtrlObj.SubType = 1; // Nb divisions
          MeshCtrlObj.SizingType = 1; //Hard
          MeshCtrlObj.NDiv = NbDivisons; // Nb divisions            
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + cntlName + ")";
          ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
      }
    }
    else{
      if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
    }
  }
  if (SizingEdgeArr.length) {
    sm.Clear();
    for (var i = 0; i < SizingEdgeArr.length; ++i) {
      sm.AddToSelection(partIdInt, SizingEdgeArr[i].Id, false);
    }
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    var cntlName = vlayerName + "-sizing";
    for (var j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      if (meshctrl.ControlType != ds.Script.id_Size)
          continue;
      var str = new String(meshctrl.Name);
      if (str.indexOf(cntlName) == -1) continue;
      MeshCtrlObj = meshctrl;
    }
    if(!MeshCtrlObj){
      if(!IsRegen){
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
          MeshCtrlObj.ESize = (VlayerSize * 2. / 3.); // specify your size specifycation
          MeshCtrlObj.SizingType = 1; //Hard
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + vlayerName + "-sizing)";
          ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
      }
    }
    else{
      if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
    }
  }  
}

function ICDefinePortMesh(meshSize, oldApproach) {
  var i, j, k, str1;
  var nsl, ns;
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var found;
  var Assys, Assy;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  // Port Meshing
  //=============================      
  found = false;
  sm.Clear();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if ((str1.indexOf("intf-") != -1) && ((str1.indexOf("-fluid-port") != -1) || (str1.indexOf("-ob-tri") != -1))) {
      found = true;
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        sm.AddToSelection(partid, topid, false);
      }
    }
  }
  if (found) {
    //Body sizing
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
    if (MeshCtrlObj) {
      MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
      MeshCtrlObj.ESize = VlayerSize; // specify your size specifycation
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (intf-port-ibVlayer)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }

  //  if (oldApproach) return;
  //Sweep for bottom ports.
  var pos, partid, partIdInt, part;
  var attrs, attr;
  var face/*IABrFace*/, edges, edge, body, bodies, faces;

  var facesArr, partArr, bodiesArr, wallfaceArr, wallPartArr, wallNSArr;
  facesArr = new Array();
  partArr = new Array();
  bodiesArr = new Array();
  wallfaceArr = new Array();
  wallPartArr = new Array();
  wallNSArr = new Array();
  DefineOrResetPortInflationCtrl(facesArr, partArr, bodiesArr, wallfaceArr, wallPartArr, wallNSArr);

  //1 Virtual faces for bottom mesh parts
  //========================================
  if (0) {
    i = 0;
    var curNS, topoArrNS, partArrNS, topoVCArr, partVCArr, topoVCArr1;
    topoVCArr = new Array();
    partVCArr = new Array();
    while (i < wallfaceArr.length) {
      topoArrNS = new Array();
      partArrNS = new Array();
      curNS = wallNSArr[i];
      for (; i < wallfaceArr.length; ++i) {
        if (wallNSArr[i] != curNS) break;
        topoArrNS.push(wallfaceArr[i]);
        partArrNS.push(wallPartArr[i]);
      }
      ns = nsl.item(curNS);

      topoVCArr1 = ICCreateVirtualCellForNS(ns, topoArrNS, partArrNS);
      for (j = 0; j < topoVCArr1.length; ++j) {
        topoVCArr.push(topoVCArr1[j]);
        partVCArr.push(partArrNS[0]);
      }
    }
    wallfaceArr = topoVCArr;
    wallPartArr = partVCArr;
  }

  // Do not set the sweep method if the bodies are not sweepable
  sm.Clear();
  meshGroup.PreviewSweepable(sm);
  var partId, sweepPartArr,sweepBodyArr;
  sweepBodyArr = new Array();
  sweepPartArr = new Array();
  var facesArrTmp = new Array();
  var partArrTmp = new Array();
  var bodiesArrTmp = new Array();
  for (i = 1; i <= sm.SelectedCount; i++) {
    sweepBodyArr.push(sm.SelectedEntityTopoID(i));
    sweepPartArr.push(sm.SelectedPartID(i));
  }
  var nonSweepPartArr,nonSweepBodyArr;
  nonSweepPartArr = new Array();
  nonSweepBodyArr = new Array();
  for (i = 0; i < facesArr.length; ++i) {
    var NbSweepable=0;
    for (j = 0; j < sweepPartArr.length; ++j) {
      if (sweepPartArr[j] == partArr[i]){
        if((bodiesArr[2 * i].Id==sweepBodyArr[j])||
           (bodiesArr[2 * i+1].Id==sweepBodyArr[j]))
          ++NbSweepable;
      }
    }
    if (NbSweepable == 2) {
      facesArrTmp.push(facesArr[i]);
      partArrTmp.push(partArr[i]);
      bodiesArrTmp.push(bodiesArr[2 * i]);
      bodiesArrTmp.push(bodiesArr[2 * i + 1]);
    }
    else{
      nonSweepBodyArr.push(bodiesArr[2 * i]);
      nonSweepPartArr.push(partArr[i]);
      nonSweepBodyArr.push(bodiesArr[2 * i + 1]);
      nonSweepPartArr.push(partArr[i]);
    }
  }
  sm.Clear();
  for (i = 0; i < nonSweepPartArr.length; ++i) {
    sm.AddToSelection(nonSweepPartArr[i], nonSweepBodyArr[i].Id, false);
  }
  if (sm.SelectedCount) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.ESize = IbSize; // specify your size specifycation
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (port-bottom)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  if (facesArrTmp.length == 0 ) return;

  facesArr = facesArrTmp;
  partArr = partArrTmp;
  bodiesArr = bodiesArrTmp;
  if (oldApproach) {
    createSweepForPortBottom(facesArr, partArr, bodiesArr);
    return;
  }

  //2 Split the edges and create hard sizing
  //========================================
  // Fill the target faces also, because we have to split the target edges as well.
  var facesArr1, partArr1;
  facesArr1 = new Array();
  partArr1 = new Array();
  for (i = 0; i < facesArr.length; ++i) {
    faces = bodiesArr[2 * i].Faces;
    for (j = 1; j <= faces.Count; ++j) {
      face = faces.item(j);
      if (face.Id == facesArr[i].Id) continue;
      bodies = face.Bodies;
      if (bodies.Count != 2) continue;
      if (((bodiesArr[2 * i].Id == bodies.item(1).Id) && (bodiesArr[2 * i + 1].Id == bodies.item(2).Id))
            || ((bodiesArr[2 * i + 1].Id == bodies.item(1).Id) && (bodiesArr[2 * i].Id == bodies.item(2).Id))) {
        facesArr1.push(face);
        partArr1.push(partArr[i]);
        break;
      }
    }
  }
  facesArr1 = facesArr1.concat(facesArr);
  partArr1 = partArr1.concat(partArr);

  var lCommonEdge = false, length;
  var edgeArr, edgePartArr;
  edgesArr = new Array();
  edgePartArr = new Array();
  var edgeArrOri = new Array();
  var edgePartArrOri = new Array();

  for (i = 0; i < facesArr1.length; ++i) {
    edges = facesArr1[i].Edges;
    for (j = 1; j <= edges.Count; ++j) {
      edgeArrOri.push(edges.item(j).Id);
      edgePartArrOri.push(partArr1[i]);
    }

    lCommonEdge = false;
    for (j = 1; j <= edges.Count; j++) {
      edge = edges.item(j);
      length = IcGetEdgeLengthAMPUnits(edge.Id, partArr1[i]);
      bodies = edge.Bodies;
      if (bodies.Count == 3) {
        lCommonEdge = true;
        break;
      }
    }
    if (!lCommonEdge) continue;

    vetex = edge.StartVertex;
    faces = vetex.Faces;
    var outerVertex = false;
    for (j = 1; j <= faces.Count; j++) {
      for (k = 0; k < wallfaceArr.length; ++k) {
        if (wallPartArr[k] == partArr1[i]) {
          if (wallfaceArr[k] == faces.item(j).Id)
            break;
        }
      }
      if (k < wallfaceArr.length) {
        outerVertex = true;
        break;
      }
    }
    var reverse = true;
    if (edge.CurveType == 1)//Line
    {
      if ( IcAreDoublesEqual(edge.Curve.StartPoint.X, vetex.Point.X)
            && IcAreDoublesEqual(edge.Curve.StartPoint.Y, vetex.Point.Y)
            && IcAreDoublesEqual(edge.Curve.StartPoint.Z, vetex.Point.Z)) {
        reverse = false;
      }
    }

    var ratio;
    if (outerVertex)
      ratio = (meshSize/2.0) / length;
    else
      ratio = 1 - ((meshSize/2.0) / length);
    if (reverse)
      ratio = 1 - ratio;

    sm.Clear();
    sm.AddToSelection(partArr1[i], edge.Id, false);
    var vcell = ICEVirtualSplitEdge();
    if (vcell) {
      vcell.SplitEdgeRatio = ratio;
      var edgesNb = new Array();
      edges = facesArr1[i].Edges; //sweep source face new edges
      for (j = 1; j <= edges.Count; ++j) {
        for (k = 0; k < edgeArrOri.length; ++k) {
          if (partArr1[i] != edgePartArrOri[k])
            continue;
          if (edges.item(j).Id == edgeArrOri[k])
            break;
        }
        if (k == edgeArrOri.length)
          edgesNb.push(j);
      }
      if (edgesNb.length == 2) {
        if (edges.item(edgesNb[0]).Length > edges.item(edgesNb[1]).Length) {
          edgesArr.push(edges.item(edgesNb[1]).Id);
        }
        else {
          edgesArr.push(edges.item(edgesNb[0]).Id);
        }
        edgePartArr.push(partArr1[i]);
      }
    }
  }

  //Edge sizing
  if (edgesArr.length) {
    sm.Clear();
    for (i = 0; i < edgesArr.length; ++i) {
      sm.AddToSelection(edgePartArr[i], edgesArr[i], false);
    }
    var MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.SubType = 1; // Nb divisions
      MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlObj.NDiv = NbInflation; // Nb divisions
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (inflation-port)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }

  createSweepForPortBottom(facesArr, partArr, bodiesArr);
  
  // Edge sizing sweep bodies edges
  var wallEdgeArr, wallEdgePartArr;
  wallEdgeArr = new Array();
  wallEdgePartArr = new Array();
  /*for (i = 0; i < wallfaceArr.length; ++i) {
  part = Assy.PartById(wallPartArr[i]);
  face = part.BRep.Cell(wallfaceArr[i]);
  edges = face.Edges;
  for (j = 1; j <= edges.Count; ++j) {
  wallEdgeArr.push(edges.item(j).Id);
  wallEdgePartArr.push(wallPartArr[i]);
  }
  }*/
  wallEdgeArr = wallEdgeArr.concat(edgesArr);
  wallEdgePartArr = wallEdgePartArr.concat(edgePartArr);

  sm.Clear();
  for (i = 0; i < facesArr.length; ++i) {
    edges = facesArr[i].Edges;
    for (j = 1; j <= edges.Count; ++j) {
      for (k = 0; k < wallEdgeArr.length; ++k) {
        if (wallEdgePartArr[k] != partArr1[i]) continue;
        if (edges.item(j).Id == wallEdgeArr[k])
          break;
      }
      if (k == wallEdgeArr.length) {
        sm.AddToSelection(partArr[i], edges.item(j).Id, false);
      }
    }
  }
  if (0/*sm.SelectedCount*/) {//Not creating edge sizing because it causing problme in Ducati
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.ESize = meshSize * 0.5; // specify your size specifycation
      MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (port)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
}
function createSweepForPortBottom(facesArr,partArr, bodiesArr) {
  var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //3 Sweep for bottom ports & Hard sizing for source faces
  //========================================
  for (i = 0; i < facesArr.length; i++) {
    sm.Clear();
    sm.AddToSelection(partArr[i], bodiesArr[2 * i].Id, false);
    sm.AddToSelection(partArr[i], bodiesArr[2 * i + 1].Id, false);

    //Sweep method
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (!MeshCtrlObj) continue;
    MeshCtrlObj.Value = 5;
    MeshCtrlObj.SourceTargetSelection = 1;

    //Source geometry
    sm.Clear();
    sm.AddToSelection(partArr[i], facesArr[i].Id, false);
    MeshCtrlObj.SourceGeometry = sm;

    MeshCtrlObj.SweepShape = 1; //DE31205 Using Quad/Tri instead of Tri
    MeshCtrlObj.SweepBiasType = 3;
    MeshCtrlObj.SweepBiasValue = 1.0;
    MeshCtrlObj.SweepESizeType=0; //Element size, 1-number of division
    MeshCtrlObj.ESize = VlayerSize;
    MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);

    str1 = Assy.PartById(partArr[i]).Name;
    str1 = getBodyName(partArr[i], bodiesArr[2 * i].Id);
    str1 = str1.substring(0, str1.length - 5); //remove -body
    MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + str1 + ")";
    ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);

    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
    if (!MeshCtrlObj) continue;
    MeshCtrlObj.ESize = VlayerSize / 2.0; // specify your size specifycation
    MeshCtrlObj.SizingType = 1; //Hard
    MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
    MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + str1 + "-sweep-src)";
    ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
  }
}
function ICCreateVirtualCellForNS(ns, topoArr, partArr) {
  var partIds, topoIds, topoVCArr, topoNonVCArr;
  var Assys, Assy;
  var i,j;

  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  partIds = new Array();
  topoIds = new Array();
  topoVCArr = new Array();
  topoNonVCArr = new Array();
  for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
    str1 = String(ns.GetUnsuppressedPartTopoPair(i));
    var pos = str1.indexOf(";");
    partIds.push(str1.substring(0, pos));
    topoIds.push(topid = str1.substring(pos + 1));
  }
  if (partIds.length == 0) return;

  var partId = parseInt(partIds[0]);
  var part = Assy.PartById(partId);
  if (!part) return;

  var bodies = new Array();
  var bodiesDone = new Array();
  for (i = 0; i < partArr.length; i++) {
    var topoId = parseInt(topoArr[i]);
    var topoCell = part.BRep.Cell(topoId);
    var cellBodies = topoCell.Bodies;
    if (!cellBodies.Count) continue;
    var body = cellBodies.Item(1);
    bodies.push(body);
  }

  var refArr = new Array();
  for (i = 0; i < bodies.length; i++) {
    lcontinue = true;
    sm.Clear();

    for (j = 0; j < bodiesDone.length; j++) {
      if (bodiesDone[j] == bodies[i])
        lcontinue = false;
    }
    if (!lcontinue) continue;

    bodiesDone.push(bodies[i]);
    sm.AddToSelection(partArr[i], topoArr[i], false);
    var tmpArr = new Array();
    tmpArr.push(topoArr[i]);

    for (j = i + 1; j < bodies.length; j++) {
      if (bodies[i] != bodies[j])
        continue;
      sm.AddToSelection(partArr[j], topoArr[j], false);
      tmpArr.push(topoArr[j]);
    }
    var vCell;
    if (sm.SelectedCount > 1)
      vCell = ICEAddVirtualFace();
    if (vCell && vCell.RefId)
      refArr.push(vCell.RefId);
    else {
      topoNonVCArr = topoNonVCArr.concat(tmpArr);
    }
  }

  sm.Clear();
  for (i = 0; i < partIds.length; i++) {
    sm.AddToSelection(partIds[i], topoIds[i], false);
  }
  for (i = 0; i < refArr.length; i++) {
    topoId = part.GetTopoId(refArr[i]);
    topoVCArr.push(topoId);
    sm.AddToSelection(partId, topoId, false);
  }
  if(refArr.length)
    ns.GeometrySelection = sm;
  topoVCArr = topoVCArr.concat(topoNonVCArr);

  return topoVCArr;
}
function ICECreateVirtualFacesForVlyer() {
  var i, j, k, str1, assy, assys, parts;
  var part, faces, face, faceArr, faceArr1, BodyArr, virFaces;
  var cellBodies;
  var attrs, attr, l;

  assys = pm.assemblies;
  if (assys.Count)
    assy = assys.Item(1);
  parts = assy.Parts(true);
  for (i = 1; i <= parts.Count; ++i) {
    part = parts.Item(i);
    str1 = String(part.Name);
    if (str1.indexOf("vlayer") == -1) continue;
    faces = part.BRep.Cells(2);
    if (faces.Count == 0) continue;

    var sourceFaces = new Array();
    var attrs = part.AttributesByName(1,"ICEngine_SweepSources");
    for (j = 1; j <= attrs.Count; ++j) {
      attr = attrs.item(j);
      sourceFaces.push(attr.TopoId);
    }
    faceArr = new Array();
    faceArr1 = new Array();
    BodyArr = new Array();
    for (j = 1; j <= faces.Count; j++) {
      face = faces.Item(j);
      cellBodies = face.Bodies;
      if (cellBodies.Count == 2) {
        faceArr.push(face);
        BodyArr.push(cellBodies.Item(1));
        BodyArr.push(cellBodies.Item(2));
      }
    }
    for (j = 0; j < faceArr.length; j++) {

      for (k = 0; k < faceArr1.length; k++) {
        if (faceArr1[k] == faceArr[j]) break;
      }
      if (k < faceArr1.length) continue;

      sm.Clear();

      for (k = j + 1; k < faceArr.length; k++) {
        for (l = 0; l < sourceFaces.length; ++l) {
          if (sourceFaces[l] == faceArr[j].Id || sourceFaces[l] == faceArr[k].Id)
            break;
        }
        if (l < sourceFaces.length) continue; //These are vertical sweep source faces, do not create vc
        if (((BodyArr[2 * j] == BodyArr[2 * k]) && (BodyArr[2 * j + 1] == BodyArr[2 * k + 1]))
          || ((BodyArr[2 * j + 1] == BodyArr[2 * k]) && (BodyArr[2 * j] == BodyArr[2 * k + 1]))
          ) {
          sm.AddToSelection(part.Id, faceArr[k].Id, false);
          faceArr1.push(faceArr[k]);
        }
      }

      sm.AddToSelection(part.Id, faceArr[j].Id, false);
      if (sm.SelectedCount > 1) {
        ICEAddVirtualFace();
      }
    }
  }
}
function ICECreateVirtualFaces() {
  var i, l, j, ns, str1, lcontinue, Assy, Assys;
  var nsl = ds.Tree.FirstActiveBranch.Components;

  var VCellGroup = ds.Tree.FirstActiveBranch.VirtualCellGroup;
  if (!VCellGroup)
    ds.Script.doInsertVTGroup(ds.Tree.FirstActiveBranch.Model);

  Assys = pm.assemblies;
  if (Assys.Count)
    Assy = Assys.Item(1);

  for (l = 1; l <= nsl.Count; ++l) {
    lcontinue = false;

    ns = nsl.item(l);
    str1 = String(ns.Name);
    if ((str1.indexOf("-ob-fluid-vlayer") != -1)) {
      lcontinue = true;
    }
    else {
      str2 = str1.substring(0, 7);
      if (((str2.indexOf("invalve") != -1) || (str2.indexOf("exvalve") != -1)) && ((str1.indexOf("-ob") != -1) || (str1.indexOf("-ib") != -1)))
        lcontinue = true;
      //str2 = str1.substring(0, 5);
      if (str1.indexOf("-seat") != -1)
        lcontinue = true;
      //if (str1.indexOf("cyl-quad") == 0)
        //lcontinue = true;
    }
    //Port faces connected to OB
    if (!lcontinue) {
      //we are not creating virtual faces for port bottom (Rally defect DE13087)
      /*if ((str1.indexOf("intf-") != -1) && (str1.indexOf("-ob-fluid-port") != -1))
        lcontinue = true;*/
      /*if (str1.indexOf("stem") != -1)
      lcontinue = true;*/
    }
    if (!lcontinue) continue;
    var partIds = new Array();
    var topoIds = new Array();
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      var pos = str1.indexOf(";");
      partIds.push(str1.substring(0, pos));
      topoIds.push(topid = str1.substring(pos + 1));
    }
    if (partIds.length == 0) continue;
    ICCreateVirtualCellForNS(ns, topoIds, partIds);
  }
}

function ICECreatePinch() {
  var i, j, k, l, protoGroup, childList, proto, child, protoList, sweepBodies, bodies;
  var attrs, attr, face;
  var allProtoArr, reqProtoArr;

  allProtoArr = new Array();
  reqProtoArr = new Array();

  protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  childList = protoGroup.Children;
  for (i = 1; i <= childList.Count; i++) {
    partProto = childList.Item(i);
    if (ds.Script.id_BodyGroup != partProto.Class) continue;

    protoList = partProto.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    str1 = String(partProto.Name);
    if (str1 == "piston-layer" || str1 == "ch Bodies" ) {
      for (j = 1; j <= protoList.count; ++j)
        reqProtoArr.push(protoList.item(j));
      continue;
    }
    else if(str1.indexOf("port") != -1)
    {
      proto = partProto;
      attrs = proto.part.AttributesByName(1,"ICEngine_SweepSources");
      var sweepBodyIdArr = new Array();
      for (j = 1; j <= attrs.Count; ++j) {
        attr = attrs.item(j);
        face = proto.part.BRep.Cell(attr.TopoId);
        sweepBodies = face.Bodies;
        for(var k=1; k<=sweepBodies.Count; k++)
          sweepBodyIdArr.push(sweepBodies.item(k).Id);
//        if (sweepBodies.count) break;
      }

      if (!sweepBodyIdArr.length) {
        for (j = 1; j <= protoList.count; ++j)
          reqProtoArr.push(protoList.item(j));
        continue;
      }

      for (j = 1; j <= protoList.Count; j++) {
        proto = protoList.item(j);
        bodies = proto.Part.BRep.Bodies;
        if (protoList.Count != bodies.Count)
          continue;
        if(FindInArray(sweepBodyIdArr,bodies.item(j).Id) != -1){
          allProtoArr.push(proto);
        }
        else
          reqProtoArr.push(proto);
      }
    }
    else{
      for (j = 1; j <= protoList.count; ++j)
        allProtoArr.push(protoList.item(j));
    }
  }

  for (i = 0; i < allProtoArr.length; ++i) {
    proto = allProtoArr[i];
    if (!proto.Suppressed)
      proto.Suppressed = true;
  }
  for (i = 0; i < reqProtoArr.length; ++i) {
    proto = reqProtoArr[i];
    if (proto.Suppressed)
      proto.Suppressed = false;
  }

  ICEDoAutoPinch();

  //remove unwanted pintch
  //  var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  //  var mehctrls = meshGroup.MeshControls;
  //  var ctrl;
  //  for (j = 1; j <= mehctrls.Count; j++) {
  //    ctrl = mehctrls.item(j);
  //    if (ctrl.ControlType == 33) {
  //      if (!ctrl.PinchSnapBoundary) {
  //        ds.Script.changeActiveObject(ctrl.ID);
  //        doEditDelete();
  //      }
  //    }
  //  }

  for (i = 0; i < allProtoArr.length; ++i) {
    proto = allProtoArr[i];
    if (proto.Suppressed)
      proto.Suppressed = false;
  }

}

function ICECreateVirtualEdgesObsolete(optioforChLower) {

  var i, j, k, l, m, n, protoGroup, childList, proto, child, protoList, bodies, loopCont, branch, VCellGroup;
  var bodies, body, edges, edge, edge1, topoId, faces, faces1;

  protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  branch = ds.Tree.FirstActiveBranch;
  VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup)
    ds.Script.doInsertVTGroup(ds.Tree.FirstActiveBranch.Model);

  childList = protoGroup.Children;

  //Hide everthing
  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);

    if (ds.Script.id_Prototype == child.Class) {
      proto = child;
      if (!proto.Suppressed && !proto.Hidden) {
        proto.Hidden = true;
        ds.Script.updateOneNodeState(proto.ID)
      }
    }
    else if (ds.Script.id_BodyGroup == child.Class) {
      protoList = child.Prototypes;
      for (j = 1; j <= protoList.Count; j++) {
        proto = protoList(j);
        if (!proto.Suppressed && !proto.Hidden) {
          proto.Hidden = true;
          ds.Script.updateOneNodeState(proto.ID)
        }
      }
    }
  }

  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);

    if (ds.Script.id_BodyGroup != child.Class) continue;

    var partName = String(child.Name);
//    if ((partName.indexOf("-vlayer") == -1) && (partName.indexOf("-ib") == -1) && (partName.indexOf("-layer") == -1) && (partName.indexOf("ch-lower") == -1)) {
//        continue;
    if ((partName.indexOf("-vlayer") == -1) && (partName.indexOf("-ib") == -1) && (partName.indexOf("-layer") == -1) &&  (partName.indexOf("ch-lower") == -1)) {
        continue;
    }
    if ((partName.indexOf("ch-lower") != -1) && (optioforChLower != 1)) {
        continue;
    }
    
    protoList = child.Prototypes;
    for (var j = 1; j <= protoList.Count; j++) {
      proto = protoList(j);
      if (partName.indexOf("-layer") != -1) {
        str1 = String(proto.Name);
        if (str1.indexOf("layer-cylinder") == -1) //create vc for layer-cylinder only.
          continue;
      }
      if (!proto.Suppressed && proto.Hidden) {
        proto.Hidden = false;
        ds.Script.updateOneNodeState(proto.ID)
      }
      bodies = proto.Part.BRep.Bodies;
      if (protoList.Count != bodies.Count)
        continue;
      body = bodies.item(j);
      edges = body.Edges;
      arr = new Array();
      count = 0;
      for (k = 1; k <= edges.Count; k++) {
        edge = edges.item(k);
        if (edge.CurveType == 8)//kABrCurveFaceted, i.e edge created by virtual topology, we should not merge the edge created by vt.
          continue;
        loopCont = false;
        for (l = 1; !loopCont && l < arr.length; l++) {
          if (arr[l] == edge.Id) loopCont = true;
        }
        if (loopCont) continue;
        sm.Clear();
        sm.AddToSelection(proto.Part.Id, edge.Id, false);
        faces = edge.Faces;
        //ds.Script.doGraphicsAdjacentSelectRecursive();
        sm.floodSelect(45.);
        if (sm.SelectedCount <= 1) continue;

        for (l = 2; l <= sm.SelectedCount; l++) {
          topoId = sm.SelectedEntityTopoID(l);
          edge1 = proto.part.BRep.Cell(topoId);
          faces1 = edge1.Faces;
          for (m = 1; m <= faces.Count; ++m) {
            for (n = 1; n <= faces1.Count; ++n) {
              if (faces.item(m).Id == faces1.item(n).Id)
                break;
            }
            if (n > faces1.Count) break;
          }
          if (m <= faces.Count) //Not found
          {
            sm.RemoveFromSelection(proto.Part.Id, topoId);
            l--;
          }
          else {
            arr.push(sm.SelectedEntityTopoID(l));
          }
        }
        ICEAddVirtualFace();
      }
      if (!proto.Suppressed && !proto.Hidden) {
        proto.Hidden = true;
        ds.Script.updateOneNodeState(proto.ID)
      }
    }
  }

  if (typeof (ds.Script.lv) != "undefined")
      ds.Script.doShowAllParts();

}

function ICEAddVirtualFace() {
  var vCell;

  var branch = ds.Tree.FirstActiveBranch;
  if(!branch){
    if (ds.Tree.Branches.Count)
      branch = ds.Tree.Branches.Item(1);
  }

  var VCellGroup = null;
  if (branch)
    VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup) {
    ds.Script.doInsertVTGroup(ds.Tree.FirstActiveBranch.Model);
    VCellGroup = branch.VirtualCellGroup;
    if (!VCellGroup) {
      // couldn't find object
      ds.WBScript.Out(localString("ds.Script.id_CannotFindObject"), true);
      //ds.Script.endWaitCursor();
      return;
    }
  }

  bHandleNodeClick = false;
  try {
    vCell = VCellGroup.CreateVirtualCell(sm);
    if (vCell) {
      var cellNode = ds.Script.GetNode(VCellGroup.ID);
      // fixed defect : 60278
      //ds.Script.addNodeAndChildren(vCell, cellNode);
      ds.Script.expandBranch(VCellGroup.ID);

      if (vCell.IsCompound || (vCell.VTClass == 2)) {
        ds.Script.updateVirtualTopologyGroup(VCellGroup);
      }
      ds.Script.changeActiveObject(vCell.ID);
      vCell.ProjectToGeometry = VCProjectToGeometry;
    }
  }
  catch (e) {
  }

  //  if (VCellGroup.HasError)
  //    wbErrorMsgBox(wbGetLocalString(stringTable, VCellGroup.ErrorString),
  //                      wbGetLocalString(stringTable, "ds.Script.id_DesignSpaceError"));

  sm.Clear();
  return vCell;
}
function ICEVirtualSplitEdge() {
  if (sm.Edges == 0) {
    wbInfoMsgBox(localString("ds.Script.id_NoSelectionForSplitEdge"),
                      localString("ds.Script.id_DesignSpace"));
    return;
  }

  if (sm.Edges > 1) {
    wbInfoMsgBox(localString("ds.Script.id_NoMultiSelectionForSplitEdge"),
                      localString("ds.Script.id_DesignSpace"));
    return;
  }

  var branch = ds.Tree.FirstActiveBranch;
  var VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup || (VCellGroup.Class != ds.Script.id_VirtualCellGroup)) {
    // couldn't find object
    WBScript.Out(localString("ds.Script.id_CannotFindObject"), true);
    return;
  }

  var vCell;
  try {
    vCell = VCellGroup.CreateVirtualSplitEdge(sm, 0);
    if (vCell) {
      var cellNode = ds.Script.GetNode(VCellGroup.ID);
      //ds.Script.addNodeAndChildren(vCell, cellNode);      
      ds.Script.expandBranch(VCellGroup.ID);

      ds.Script.changeActiveObject(vCell.ID);
    }
  }
  catch (e) {
  }

  sm.Clear();

  return vCell;
}
function ICECreateAutomaticVC(createVCforAllBodies) {
  var branch, VCellGroup;
  var Assys, Assy, nsl, ns, partId, topoId;
  var part;
  var i, j, k, l;
  var vCells, vCell, sel, found, pos;
  var facesOld, facesNew, faceArr;
  var nsArr, vcArr;

  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //Automatic virtual cell creation
  branch = ds.Tree.FirstActiveBranch;
  VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup)
    ds.Script.doInsertVTGroup(ds.Tree.FirstActiveBranch.Model);
  VCellGroup = branch.VirtualCellGroup;
  VCellGroup.Behavior = VT/*2*/;

  ds.Script.changeActiveObject(VCellGroup.ID);

  var protoGroup, proto, childList, child, allProtoArr, reqProtoArr;
  var str1;

  if (createVCforAllBodies)
    VCellGroup.AutoGenerateVirtualCells();
  else {
    allProtoArr = new Array();
    reqProtoArr = new Array();

    protoGroup = ICGetProtoGroup();
    if (!protoGroup)
      return;

    childList = protoGroup.Children;
    for (i = 1; i <= childList.Count; i++) {
      child = childList.Item(i);
      if (ds.Script.id_BodyGroup != child.Class) continue;

      protoList = child.Prototypes;
      if (!protoList || !protoList.count)
        continue;

      str1 = String(child.Name);
      if ((str1.indexOf("-port-") != -1)|| (str1.indexOf("Single-Zone") != -1)) {
        reqProtoArr.push(child);
      }
      else {
        for (j = 1; j <= protoList.count; ++j) {
          allProtoArr.push(protoList.item(j));
        }
      }
    }
    var partBodyArr = new Array();
    for (i = 0; i < reqProtoArr.length; ++i) {
      proto = reqProtoArr[i];
      protoList = proto.Prototypes;
      bodies = proto.Part.BRep.Bodies;
      for (j = 1; j <= bodies.Count; ++j) {
        body = bodies.Item(j);
        var str = protoList.item(j).Name;
        if (str.indexOf("Port") == 0) {
          partBodyArr.push(proto.Part.Id);
          partBodyArr.push(body.Id);
        }
      }
    }

    VCellGroup.AutoGenerateVirtualCells();

    vCells = VCellGroup.VirtualCells;
    if (!vCells.Count) return;
    for (i = 1; i <= vCells.Count; i++) {
      var deleteIt = true;
      var vCell = vCells.item(i);
      var part = Assy.PartById(vCell.PartId);
      var topoId = part.GetTopoId(vCell.RefId);
      if (topoId <= 0) continue;
      var topoCell = part.BRep.Cell(topoId);
      var cellBodies = topoCell.Bodies;
      if (cellBodies.Count < 1) continue;
      var body = cellBodies.item(1);
      for (k = 0; k < partBodyArr.length; ++k) {
        if (partBodyArr[k++] != vCell.PartId)
          continue;
        if (partBodyArr[k] == body.Id) {
          deleteIt = false;
          break;
        }
      }
      if (!deleteIt)
        continue;
      //if(vCell.Suppressed)
      VCellGroup.DeleteVCellAndDependents(vCell.ID);
    }
    vCells = VCellGroup.VirtualCells;
    if(vCells.Count == 0){
      //DE77335 delete the vt group to update ns faces
      if (ds.Tree.CanDelete(VCellGroup.ID))
        ds.Tree.DeleteItem(VCellGroup.ID);
      IcActivateBranch();
      ds.Script.doInsertVTGroup(ds.Tree.FirstActiveBranch.Model);
      VCellGroup = branch.VirtualCellGroup;
      VCellGroup.Behavior = VT;
    }
  }

}

function ICStoreNsFacesBeta() {
  var branch = ds.Tree.FirstActiveBranch;
  var VCellGroup = branch.VirtualCellGroup;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if(nsl.Count==0) return;
  if(VCellGroup){
    vCells = VCellGroup.VirtualCells;
    for (var i = vCells.Count; i >= 1; i--) {
      vCell = vCells.item(i);
      vCell.Suppressed = true;
    }
  }
  originalNsFaces = new Array(nsl.Count);
  for (var i = 0; i < originalNsFaces.length; ++i) {
    originalNsFaces[i] = new Array();
  }
  for (var j = 1; j <= nsl.Count; ++j) {
    var ns = nsl.item(j);
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      var str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      var pos = str1.indexOf(";");
      var partId = parseInt(str1.substring(0, pos));
      var topoId = parseInt(str1.substring(pos + 1));
      originalNsFaces[j-1].push(partId);
      originalNsFaces[j-1].push(topoId);
    }
  }
  if(VCellGroup){
    vCells = VCellGroup.VirtualCells;
    for (var i = vCells.Count; i >= 1; i--) {
      vCell = vCells.item(i);
      vCell.Suppressed = false;
    }
  }
}
function ICUpdateNSWithVCBeta() {
  var vCells, vCell, sel, found, pos;
  var facesOld, facesNew, faceArr;
  var nsArr, vcArr;
  var branch, VCellGroup;
  var Assys, Assy, nsl, ns, partId, topoId;
  var part;
  var i, j, k, l;
  var vCells, vCell, sel, found, pos;

  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //Automatic virtual cell creation
  branch = ds.Tree.FirstActiveBranch;
  VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup) return;

  ds.Script.changeActiveObject(VCellGroup.ID);

  nsl = ds.Tree.FirstActiveBranch.Components;

  if (!VCellGroup) return;
  if (!nsl.Count) return;

  nsArr = new Array(nsl.Count);
  for (i = 0; i < nsArr.length; ++i) {
    nsArr[i] = new Array();
  }

  vCells = VCellGroup.VirtualCells;
  if (!vCells.Count) return;
/*
  //Delete the virtual cells which are created on top of virtual cells 
  var cellsToDeleteArr = new Array();
  for (i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    part = Assy.PartById(vCell.PartId);
    if (vCell.VTClass != 2) continue; //only faces
    if (vCell.Suppressed)
      vCell.Suppressed = false;
    facesNew = part.BRep.Cells(2);
    vCell.Suppressed = true;
    facesOld = part.BRep.Cells(2);
    if (facesOld.Count == facesNew.Count)
      cellsToDeleteArr.push(vCell.ID);
    vCell.Suppressed = false;
  }
  for (i = 0; i < cellsToDeleteArr.length; i++) {
    VCellGroup.DeleteVCellAndDependents(cellsToDeleteArr[i]);
  }
  vCells = VCellGroup.VirtualCells;
  for (i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    if (vCell.Suppressed)
      vCell.Suppressed = false;
  }
*/
  var refId,topoId;
  if(originalNsFaces.length != nsl.Count) 
    return;
  for (j = 0; j < originalNsFaces.length; ++j) {
    for (k = 0; k < (originalNsFaces[j].length/2); k++) {
      if(k==0)
        part = Assy.PartById(originalNsFaces[j][2*k]);
      topoId = originalNsFaces[j][2*k+1];
      refId = part.GetReferenceId(topoId);
      //this function takes original face refid (before vc creation), and returns corresponding vc face refid
      var ret = part.getActiveGuestEntitiesRefIds2(refId)
      for(i=1; i<=ret.Count; ++i){
        nsArr[j].push(part.Id);
        nsArr[j].push(part.GetTopoId(ret.item(i)));
      }
    }
  }
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    if (nsArr[j - 1].length == 0) continue;
    sm.Clear();
    for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      pos = str1.indexOf(";");
      partId = str1.substring(0, pos);
      topoId = str1.substring(pos + 1);
      sm.AddToSelection(partId, topoId, false);
    }
    for (k = 0; k < (nsArr[j - 1].length / 2); ++k) {
      sm.AddToSelection(nsArr[j - 1][2 * k], nsArr[j - 1][2 * k + 1], false);
    }
    ns.GeometrySelection = sm;
  }
}
function ICUpdateNSWithVC() {
  var vCells, vCell, sel, found, pos;
  var facesOld, facesNew, faceArr;
  var nsArr, vcArr;
  var branch, VCellGroup;
  var Assys, Assy, nsl, ns, partId, topoId;
  var part;
  var i, j, k, l;
  var vCells, vCell, sel, found, pos;

  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //Automatic virtual cell creation
  branch = ds.Tree.FirstActiveBranch;
  VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup) return;

  ds.Script.changeActiveObject(VCellGroup.ID);

  nsl = ds.Tree.FirstActiveBranch.Components;

  if (!VCellGroup) return;
  if (!nsl.Count) return;

  nsArr = new Array(nsl.Count);
  for (i = 0; i < nsArr.length; ++i) {
    nsArr[i] = new Array();
  }

  vCells = VCellGroup.VirtualCells;
  if (!vCells.Count) return;

  //Delete the virtual cells which are created on top of virtual cells 
  var cellsToDeleteArr = new Array();
  for (i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    part = Assy.PartById(vCell.PartId);
    if (vCell.VTClass != 2) continue; //only faces
    if (vCell.Suppressed)
      vCell.Suppressed = false;
    facesNew = part.BRep.Cells(2);
    vCell.Suppressed = true;
    facesOld = part.BRep.Cells(2);
    if (facesOld.Count == facesNew.Count)
      cellsToDeleteArr.push(vCell.ID);
    vCell.Suppressed = false;
  }
  for (i = 0; i < cellsToDeleteArr.length; i++) {
    VCellGroup.DeleteVCellAndDependents(cellsToDeleteArr[i]);
  }

  vCells = VCellGroup.VirtualCells;
  for (i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    part = Assy.PartById(vCell.PartId);
    if (vCell.VTClass != 2) continue; //only faces
    if (vCell.Suppressed)
      vCell.Suppressed = false;
    facesNew = part.BRep.Cells(2);
    vCell.Suppressed = true;

    facesOld = part.BRep.Cells(2);
    faceArr = new Array();
    for (j = 1; j <= facesOld.Count; ++j) {
      id = facesOld.item(j).Id;
      for (k = 1; k <= facesNew.Count; ++k) {
        if (id == facesNew.item(k).Id)
          break;
      }
      if (k > facesNew.Count)
        faceArr.push(id);
    }
    if (!faceArr.length) continue;
    found = 0;
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(k));
        pos = str1.indexOf(";");
        partId = str1.substring(0, pos);
        if (partId != part.Id)
          break;
        topoId = str1.substring(pos + 1);
        for (l = 0; l < faceArr.length; ++l) {
          if (faceArr[l] == topoId) {
            found = j;
            break;
          }
        }
        if (found) break;
      }
      if (found) break;
    }

    vCell.Suppressed = false;
    if (found) {
      nsArr[found - 1].push(part.Id);
      nsArr[found - 1].push(part.GetTopoId(vCell.RefId));
    }
  }
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    if (nsArr[j - 1].length == 0) continue;
    sm.Clear();
    for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      pos = str1.indexOf(";");
      partId = str1.substring(0, pos);
      topoId = str1.substring(pos + 1);
      sm.AddToSelection(partId, topoId, false);
    }
    for (k = 0; k < (nsArr[j - 1].length / 2); ++k) {
      sm.AddToSelection(nsArr[j - 1][2 * k], nsArr[j - 1][2 * k + 1], false);
    }
    ns.GeometrySelection = sm;
  }

  for (i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    if (vCell.Suppressed)
      vCell.Suppressed = false;
  }

}
function ICGetIBTopBodies() {
  var i, j, k, l, str1, str2;
  var nsl, ns;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  var topBodiesArr = new Array();

  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-ib") != -1)) {
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        var name = getBodyName(partid, topid);
        if (name.indexOf("-top") == -1) 
          continue;
        topBodiesArr.push(topid);
        topBodiesArr.push(partid);
      }
    }
  }
  return topBodiesArr;
}
function ICDefineIBMesh(IsRegen) {
  var i, j, k, l, str1;
  var nsl, ns;
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var found;
  var Assys, Assy;
  var ns, name, found;
  var partid, topid, pos;
  var arr;
  var facesArr, partArr;
  var meshSize = getMeshSize();
  var oldApproach = getFluentOldApproach();

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-ib") != -1)) {
      arr.push(ns);
    }
  }
  sm.Clear();
  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      topid = str1.substring(pos + 1);
      sm.AddToSelection(partid, topid, false);
    }
  }
  if (arr.length) {
    //Body size
    var MeshCtrlObj = ICGetMeshControlByName("(ib)",ds.Script.id_Size);
    if(!MeshCtrlObj){
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
      if (MeshCtrlObj) {
        MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (ib)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }
    else{
      if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
      {
        var ctrlName = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
      }
    }
    if(!IsRegen)
      MeshCtrlObj.ESize = IbSize/*meshSize / 2.0*/; // specify your size specifycation

    var topBodiesArr = ICGetIBTopBodies();

    //Sweep method
    for (j = 0; j < arr.length; j++) {
      sm.Clear();
      ns = arr[j];
      partid = "";
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        for (k = 0; k < topBodiesArr.length / 2; k++) {
          if (topBodiesArr[2 * k + 1] != partid) continue;
          if (topBodiesArr[2 * k] == topid) break;
        }
        if (k < topBodiesArr.length / 2) continue;
        sm.AddToSelection(partid, topid, false);
      }
      if (partid == "") continue;
      var partIdInt = parseInt(partid);
      var part = Assy.PartById(partIdInt);
      var attrs = part.AttributesByName(1,"ICEngine_SweepSources");
      var attr;

      var ibName = String(ns.Name);
      ibName = ibName.substring(6, ibName.length); //remove fluid-
      //Sweep method
      var ctrlName="("+ibName+")";
      var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_BodyMeshType);
      if(!MeshCtrlObj){
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
        if (MeshCtrlObj) {
          MeshCtrlObj.Value = 5;
          MeshCtrlObj.SourceTargetSelection = 1;
          MeshCtrlObj.SweepShape = 2;
          MeshCtrlObj.SweepBiasType = 3;
          MeshCtrlObj.SweepBiasValue = 1.0;
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          MeshCtrlObj.Name = MeshCtrlObj.Name + " " + ctrlName;
          ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
      }
      else{
        if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
        {
          ctrlName = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
        }
      }
      
      //Source geometry
      sm.Clear();
      for (i = 1; i <= attrs.Count; ++i) {
        attr = attrs.item(i);
        var topid = attr.TopoId;
        face = part.BRep.Cell(topid);
        var bodies = face.bodies;
        var bodyId = bodies.item(1).Id;
        for (k = 0; k < topBodiesArr.length / 2; k++) {
          if (topBodiesArr[2 * k + 1] != partIdInt) continue;
          if (topBodiesArr[2 * k] == bodyId) break;
        }
        if (k < topBodiesArr.length / 2) continue;
        sm.AddToSelection(partIdInt, topid, false);
      }
      if(sm.SelectedCount > 0)
        MeshCtrlObj.SourceGeometry = sm;
        
      var ctrlName="("+ibName+"-sweep-src)";
      var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_Size);
      if(!MeshCtrlObj){
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
          MeshCtrlObj.SizingType = 1; //Hard
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          MeshCtrlObj.Name = MeshCtrlObj.Name + " "+ctrlName;
          ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
      }
      else{
        if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
        {
          ctrlName = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
        }
      }
      if(!IsRegen)
        MeshCtrlObj.ESize = IbSize/*meshSize / 2.0*/; // specify your size specifycation

      //Sweep method for top bodies
      sm.Clear();
      var bodiesIdArr=new Array();
      for (k = 0; k < topBodiesArr.length / 2; k++) {
        if (topBodiesArr[2 * k + 1] != partIdInt) continue;
        sm.AddToSelection(partIdInt, topBodiesArr[2 * k], false);
        bodiesIdArr.push(topBodiesArr[2 * k]);
      }
      if (bodiesIdArr.length != 2) continue;
 
      if(!sm.SelectedCount) continue;
      var ctrlName="(" + ibName + "-top)";
      var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_BodyMeshType);
      if(!MeshCtrlObj){
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
        MeshCtrlObj.Value = 5;
        MeshCtrlObj.SourceTargetSelection = 1;
        MeshCtrlObj.SweepShape = 2;
        MeshCtrlObj.SweepBiasType = 3;
        MeshCtrlObj.SweepBiasValue = 1.0;
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " " + ctrlName;
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
      else{
        if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
        {
          ctrlName = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
        }
      }      
      //Source geometry
      sm.Clear();
      for (i = 0; i < bodiesIdArr.length; ++i) {
        var body = part.BRep.Cell(bodiesIdArr[i]);
        var faces = body.faces;
        for (k = 1; k <= faces.Count; ++k) {
          var face = faces.item(k);
          var bodies = face.bodies;
          if (bodies.Count < 2) continue;
          if ( (bodies.item(1).Id == bodiesIdArr[0] || bodies.item(1).Id == bodiesIdArr[1]) &&
               (bodies.item(2).Id == bodiesIdArr[0] || bodies.item(2).Id == bodiesIdArr[1])) {
            continue;
          }
          sm.AddToSelection(partIdInt, face.Id, false);
        }
      }
      if(sm.SelectedCount > 0)
        MeshCtrlObj.SourceGeometry = sm;
    }
  }

  //Edge sizing
  var ctrlName="Edge Sizing (ib)";
  var MeshCtrlObj = ICGetMeshControlByName(ctrlName,ds.Script.id_Size);
	if(!MeshCtrlObj || MeshCtrlObj.GeometryNum == 0){
    var edgesArrTotal = createIBVirtualEdgeSplits()
    if (edgesArrTotal.length) {
      sm.Clear();
      var j = (edgesArrTotal.length / 2);
      for (i = 0; i < j; ++i) {
        sm.AddToSelection(edgesArrTotal[j + i], edgesArrTotal[i], false);
      }
      if(!MeshCtrlObj)
      {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
        MeshCtrlObj.SubType = 1; // Nb divisions
        MeshCtrlObj.SizingType = 1; //Hard
        if (oldApproach)
          MeshCtrlObj.NDiv = 1; // Nb divisions
        else
          MeshCtrlObj.NDiv = 2; // Nb divisions
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (ib)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
      else{
        if (MeshCtrlObj.GeometryNum != sm.SelectedCount)
        {
          ctrlName = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = ctrlName; //Name is getting lost after setting supports.
        }
      }
    }
  }
}
function getCreviceMeshSize() {
    var str1, i, j, str2;
    var meshSize = 10;
    var Assys = pm.assemblies;
    var Assy = Assys.Item(1);
    var Parts = Assy.Parts(true);
    var k, Part;

    var attrs = Assy.AttributesByName(1,"ICEngine_Crevice_MeshSize");
    if (attrs.Count) {
        for (j = 1; j <= attrs.Count; ++j) {
            var attr = attrs.item(j);
            meshSize = attr.Double;
            break;
        }
        return meshSize;
    }

    for (k = 1; k <= Parts.Count; ++k) {
        Part = Parts.Item(k);
        str1 = String(Part.Name);
        var attrs = Part.AttributesByName(1,"ICEngine_Crevice_MeshSize");
        for (j = 1; j <= attrs.Count; ++j) {
            var attr = attrs.item(j);
            meshSize = attr.Double;
            break;
        }
    }
    return meshSize;
}

function ICDefineFaceSizingCylCrevice(){

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;
    
    var faceMeshSize; 
    faceMeshSize = getCreviceMeshSize();
    faceMeshSize= faceMeshSize * 1.15; 
  
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;
//getting all bodies present under "crevice" part
    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            if (str1.indexOf("crevice") != -1) {
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
            }
        }
    }
   
    var faceArr = new Array();
    var facePartArr = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if (str1.indexOf("cyl-crevice") != -1) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                faceArr.push(topid);
                facePartArr.push(partid);
            }
        }
    }
//getting all faces belonging to NS "cyl-crevice and present in bodies of "crevice" part
    var part, face
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
        part = Assy.PartById(facePartArr[i]);
        face = part.BRep.Cell(faceArr[i]);

        for (j = 0; j < arrName.length; ++j) {
         if (facePartArr[i] != arrPart[j]) 
            continue;
            var bodies = face.Bodies;
            if (bodies.Count == 2)
            continue;
            if (bodies.item(1).Id == arrBody[j])
            sm.AddToSelection(arrPart[j], face.Id, false);
           
        }
    } 

    // defining face sizing 
    if (sm.SelectedCount) {
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("CylCrevice") == -1) continue;
        MeshCtrlObj = meshctrl;
    }
    
    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
           MeshCtrlObj.Name = MeshCtrlObj.Name + "(CylCrevice)";
           MeshCtrlObj.SizingType = 1; //Hard
            MeshCtrlObj.SourceTargetSelection = 1;
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }
    MeshCtrlObj.ESize = faceMeshSize;
   }
}

function  ICDefineCreviceThinSweepMesh() {

  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var i, j;
  var partId;

  var Assys = pm.assemblies;
  if (Assys.Count < 1)
    return;

  var Assy = Assys.Item(1);

  var arrName = new Array();
  var arrBody = new Array();
  var arrPart = new Array();

  var MeshCtrlGrpNode;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      arrPart.push(proto.Part.Id);
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }

  //check for sweepable bodies
  /*sm.Clear();
  meshGroup.PreviewSweepable(sm);
  var sweepArr;
  sweepArr = new Array();
  var facesArrTmp = new Array();
  var partArrTmp = new Array();
  var bodiesArrTmp = new Array();
  for (i = 1; i <= sm.SelectedCount; i++) {
    sweepArr.push(sm.SelectedEntityTopoID(i)); //gets sweepable bodies id
  }*/
  
  sm.Clear();
  var bodyreq = -1, bodyName, bodyPartID;
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if (str1.indexOf("crevice") != -1) {
      bodyName = str1;
      bodyreq = arrBody[i];
      bodyPartID = arrPart[i];
      sm.AddToSelection(bodyPartID, bodyreq, false);
    }
  }
  if (bodyreq<0) return;
  
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  var MeshCtrlObj = null; 
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("crevice") == -1) continue;
    MeshCtrlObj = meshctrl;
  }

  if (!MeshCtrlObj) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 5;
      MeshCtrlObj.SourceTargetSelection = 3; //thinsweep 
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (crevice)";
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  else {
    var str1 = MeshCtrlObj.Name;
    MeshCtrlObj.GeometrySelection = sm;
    MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
  }
  MeshCtrlObj.NDiv = CreviceNoOfLayers;
  
  
 //no source geometry required for thin sweep so commented below code
  /*var pos;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  sm.Clear();
  var part, face
  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if (str1.indexOf("intf-piston-on-crevice") != -1) {
      for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        part = Assy.PartById(partid);
        face = part.BRep.Cell(topid);
        sm.AddToSelection(partid, face.Id, false);
      }
    }
  }


  if ((sm.SelectedCount) && (MeshCtrlObj)) {
    if(sm.SelectedCount>100){
    MeshCtrlObj.Value = 1;
    MeshCtrlObj.Name = MeshCtrlObj.Name + " (crevice)";
    ICDefineFaceSizingCrevicePatchConforming();
    }
    MeshCtrlObj.SourceGeometry = sm;
  }
  */

}

function ICDefineOrResetVlayerChSizing() {
  var i, j, k, l, str1,str2;
  var nsl, ns;
  var Assys, Assy;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;

  //finding chamber controls-------
  var mehctrls = meshGroup.MeshControls;
  arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(str1.length - 12, str1.length);
    if (str2.indexOf("-ob-fluid-ch") != -1) {
      arr.push(ns);
    }
  }
  sm.Clear();
  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      var pos = str1.indexOf(";");
      var partid = str1.substring(0, pos);
      var topid = str1.substring(pos + 1);
      sm.AddToSelection(partid, topid, false);
    }
  }
  if (!sm.SelectedCount) return;
  var MeshCtrlObj = null;
  str1 = "intf-vlayer-ch";
  for (i = 1; i <= mehctrls.Count; i++) {
    meshctrl = mehctrls.item(i);
    if (meshctrl.ControlType != ds.Script.id_Size) continue;
    str2 = new String(meshctrl.Name);
    if ((str2.indexOf(str1) != -1)) {
      MeshCtrlObj = meshctrl;
    }
  }

  if (!MeshCtrlObj) {
    //Body sizing
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
      MeshCtrlObj.ESize = IntfVlayerCh;
      //MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + str1 + ")";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  else {
    if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
      str1 = MeshCtrlObj.Name;
      MeshCtrlObj.GeometrySelection = sm;
      MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }
  }

}

function ICDefineChamberMesh(meshSize) {
  var i, j, k, l, str1;
  var nsl, ns;
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var found;
  var Assys, Assy;
  var ns, name, found,intPistonNs=0;
  var partid, topid, pos;
  var arr;
  var facesArr, partArr;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if (str1.indexOf("int-piston") == 0) {
      intPistonNs = ns;
    }
  }
  ICDefineOrResetVlayerChSizing();

  ICDefineOrResetVlayerChEdgeSizing();
  
  IceSetValveBottomSizing();
  
  //Sizing for chamber bodies
  sm.Clear();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("fluid-ch") != -1) && (str1.indexOf("fluid-ch-") == -1)) {
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        sm.AddToSelection(partid, topid, false);
      }
      break;
    }
  }
  if (sm.SelectedCount) {
    //Body sizing
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
      MeshCtrlObj.ESize = ChSize/*meshSize*/; // specify your size specifycation
      MeshCtrlObj.SizingCurvatureAngle = 18;
      MeshCtrlObj.SizingTransition = ChGrowthRate;
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (ch)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }

  //Sweep for layer-cylinder
  var bodies, protoGroup, childList, child, protoList;
  protoGroup = ICGetProtoGroup();
  childList = protoGroup.Children;
  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    var pistonType3 = 0;
    var pistonBody = -1, partId = 0;
    str1 = String(child.Name);
    if ((str1.indexOf("piston-layer") != -1) || (str1.indexOf("Single-Zone") != -1)) {
      var layerBody = -1;
      for (j = 1; j <= protoList.Count; j++) {
        proto = protoList.item(j);
        str1 = String(proto.Name);
        if (str1.indexOf("layer-cylinder") != -1) {
          layerBody = j;
        }
        else if (str1.indexOf("piston") != -1) {
          pistonBody = j;
        }
      }
      if (layerBody < 0) break;
      bodies = proto.Part.BRep.Bodies;

      sm.Clear();
      sm.AddToSelection(proto.Part.Id, bodies.item(layerBody).Id, false);
      if (pistonBody > -1) {
        pistonBody = bodies.item(pistonBody).Id;
        partId = proto.Part.Id;
      }
    }
    else if (str1.indexOf("ch Bodies") != -1) {
      sm.Clear();
      pistonType3 = 1;
    }
    else
      continue;

    //Sweep method
    var MeshCtrlObj1 = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj1) {
      if (intPistonNs && (intPistonNs.NumInSelection > 1))
        MeshCtrlObj1.Value = 7;
      else
        MeshCtrlObj1.Value = 5;
      MeshCtrlObj1.SweepESizeType = 0;
      MeshCtrlObj1.ESize = ChSize /*meshSize * 1.5*/;

      MeshCtrlObj1.SweepShape = 0; //DE38846 use all tri
      MeshCtrlObj1.SweepBiasType = 3;
      MeshCtrlObj1.SweepBiasValue = 1.0;

      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj1.Name = MeshCtrlObj1.Name + " (layer-cylinder)";
      ds.Script.addNodeAndChildren(MeshCtrlObj1, MeshCtrlGrpNode);

      //Body sizing
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
        MeshCtrlObj.ESize = ChSize/*meshSize*/; // specify your size specifycation
        MeshCtrlObj.SizingTransition = ChGrowthRate;
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (layer-cylinder)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
      if (pistonBody > -1) {
        sm.Clear();
        sm.AddToSelection(partId, pistonBody, false);
      }
      //Body sizing
      var MeshCtrlObjPiston = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
      if (MeshCtrlObjPiston) {
        MeshCtrlObjPiston.LocalAdvancedSizeFunction=1; //Curvature
        MeshCtrlObjPiston.ESize = ChSize * 1.0; 
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObjPiston.Name = MeshCtrlObjPiston.Name + " (piston)";
        ds.Script.addNodeAndChildren(MeshCtrlObjPiston, MeshCtrlGrpNode);
      }
      var MeshCtrlObjPiston2 = null;
      if (!IsPistonType1()) {
        MeshCtrlObjPiston2 = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
        if (MeshCtrlObjPiston2) {
          MeshCtrlObjPiston2.Value = 1;
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          ds.Script.addNodeAndChildren(MeshCtrlObjPiston2, MeshCtrlGrpNode);
          MeshCtrlObjPiston2.Name = MeshCtrlObjPiston2.Name + " (piston)";
        }
      }
      if (pistonType3) {
        if (MeshCtrlObj.SubValue)
          MeshCtrlObj.SubValue = false;
        if (MeshCtrlObj1.SubValue)
          MeshCtrlObj1.SubValue = false;
        if (MeshCtrlObjPiston.SubValue)
          MeshCtrlObjPiston.SubValue = false;
        if (MeshCtrlObjPiston2 && MeshCtrlObjPiston2.SubValue)
          MeshCtrlObjPiston2.SubValue = false;
      }      
    }
    break;
  }
  //------
  DefineOrResetChamberInflation();
  //----------
}
function ICDefineStraightValveChamberMesh(meshSize) {
  var i, j, k, l, str1;
  var nsl, ns;
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var found;
  var Assys, Assy;
  var ns, name, found;
  var partid, topid, pos;
  var arrLowerAndValve, arrIntfUpper, arrValveCh, arrIntfForVC, chUpper, intfBowl;
  var facesArr, partArr;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //# Need to create virtual cells for intf-rootname-ob-fluid-ch-upper faces.
  //# Define hard face sizing RefSize/2 to intf-rootname-ob-fluid-ch-upper faces.
  //# Define body sizing for ch-invalve/ch-exvalve, ch-upper and ch-lower to RefSize
  //# Need to create virtual cells for invalve1-ch/invalve1-ch (top) faces.
  //# Ch-lower is having imprints of ch-upper and pistion, we need to identify and create virtual cells.
  //# Create Sweep for ch-lower and ch-valve(specify support as top face) regions.Specify hard sizing RefSize for source faces.
  //# piston-bowl top face(intf-piston-bowl) should be given hard sizing RefSize

  arrLowerAndValve = new Array();
  arrIntfUpper = new Array();
  arrValveCh = new Array();
  arrIntfForVC = new Array();
  var arrIntfChLower = new Array();
  var intfDeck = null;
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 5);
    if ((str2.indexOf("fluid") != -1) && (str1.indexOf("fluid-ch-upper") != -1)) {
      chUpper = ns;
    }
    else if ((str2.indexOf("fluid") != -1) && (str1.indexOf("fluid-ch-") != -1)) {//lower or vavle
      arrLowerAndValve.push(ns);
    }
    else if ((str2.indexOf("intf") != -1) && (str1.indexOf("-ob-fluid-ch-upper") != -1)) {
      arrIntfUpper.push(ns);
    }
    else if ((str2.indexOf("intf") != -1) && (str1.indexOf("-ob-fluid-ch-lower") != -1)) {
      arrIntfChLower.push(ns);
    }
    else if (((str2.indexOf("inval") != -1) || (str2.indexOf("exval") != -1)) && (str1.indexOf("-ch") != -1)) {
      arrValveCh.push(ns);
    }
    else if (str1.indexOf("intf-deck-fluid-ch-lower") != -1) {
      arrValveCh.push(ns);
      intfDeck = ns;
    }
    else if (str1.indexOf("intf-piston-bowl") != -1)
      intfBowl = ns;
    else if (str1.indexOf("intf-piston-ch") != -1 || str1.indexOf("intf-piston-invalve") != -1 || str1.indexOf("intf-piston-exvalve") != -1)
      arrIntfForVC.push(ns);
  }
  if (!chUpper) //not a straight valve case
    return;

  var topoArr, partArr, topoVCArr;
  //# Need to create virtual cells for intf-rootname-ob-fluid-ch-upper faces.
  //# Define hard face sizing RefSize/2 to intf-rootname-ob-fluid-ch-upper faces.
  sm.Clear();
  topoArr1 = new Array();
  partArr1 = new Array();
  for (j = 0; j < arrIntfUpper.length; ++j) {
    ns = arrIntfUpper[j];
    topoArr = new Array();
    partArr = new Array();
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      //partArr.push(parseInt(partid));
      topid = str1.substring(pos + 1);
      //topoArr.push(parseInt(topid))
      topoArr1.push(parseInt(topid))
      partArr1.push(parseInt(partid))
    }
    /*topoVCArr = ICCreateVirtualCellForNS(ns, topoArr, partArr);
    if (topoVCArr.length == 1) {
    topoArr1.push(topoVCArr[0]);
    partArr1.push(partArr[0]);
    }*/
  }
  if (topoArr1.length) {
    sm.Clear();
    for (j = 0; j < topoArr1.length; ++j)
      sm.AddToSelection(partArr1[j], topoArr1[j], false);

    //Body sizing
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
      MeshCtrlObj.ESize = IntfVlayerCh/*meshSize / 2.0*/; // specify your size specifycation
      //MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (intf-ch-upper)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  ICDefineOrResetVlayerChEdgeSizing();
  
  //# Define body sizing for ch-invalve/ch-exvalve, ch-upper and ch-lower to RefSize
  sm.Clear();
  for (j = 0; j <= arrLowerAndValve.length; ++j) {
    if (j < arrLowerAndValve.length)
      ns = arrLowerAndValve[j];
    else
      ns = chUpper;
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      topid = str1.substring(pos + 1);
      sm.AddToSelection(partid, topid, false);
    }
  }
  if (sm.SelectedCount) {
    //Body sizing
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
      MeshCtrlObj.ESize = ChSize/*meshSize*/; // specify your size specifycation
      MeshCtrlObj.SizingCurvatureAngle = 18;
      MeshCtrlObj.SizingTransition = ChGrowthRate;
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (ch lower,upper,valve)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }

  //# Define tetmesh for ch-upper otherwise very skewed hex mesh is created by AMP (case5 cummins)
  sm.Clear();
  ns = chUpper;
  for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
    str1 = String(ns.GetUnsuppressedPartTopoPair(i));
    pos = str1.indexOf(";");
    partid = str1.substring(0, pos);
    topid = str1.substring(pos + 1);
    sm.AddToSelection(partid, topid, false);
  }
  if (sm.SelectedCount) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 1;
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (ch upper)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  
  //# Need to create virtual cells for invalve1-ch/exvalve1-ch (top) faces.
  //# Ch-lower is having imprints of ch-upper and pistion, we need to identify and create virtual cells.
  //# Create Sweep for ch-lower and ch-valve(specify support as top face) regions.Specify hard sizing RefSize for source faces.
  var topoArr1, partArr1;
  topoArr1 = new Array();
  partArr1 = new Array();
  for (j = 0; j < arrLowerAndValve.length; ++j) {
    ns = arrLowerAndValve[j];
    if (ns.NumInSelection - ns.NumSuppressedItems <= 0) continue;
    var curPartId, curTopoId;
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      curPartId = str1.substring(0, pos);
      curTopoId = str1.substring(pos + 1);
    }

    topoArr = new Array();
    partArr = new Array();
    for (k = 0; k < arrValveCh.length; ++k) {
      ns = arrValveCh[k];
      if (ns.NumInSelection - ns.NumSuppressedItems <= 0) continue;
      var curPartId;
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        if (curPartId == partid) {
          topoArr.push(parseInt(topid));
          partArr.push(parseInt(partid));
        }
      }
      if (curPartId == partid)
        break;
    }
    if (k == arrValveCh.length) //source not found
      continue;
    topoVCArr = ICCreateVirtualCellForNS(ns, topoArr, partArr);
    if (topoVCArr.length != 1)
      continue;
    topoArr1.push(topoVCArr[0]);
    partArr1.push(curPartId);

    //Sweep method
    sm.Clear();
    sm.AddToSelection(curPartId, curTopoId, false);
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 5;
      MeshCtrlObj.SourceTargetSelection = 1;

      //Source geometry
      sm.Clear();
      sm.AddToSelection(curPartId, topoVCArr[0], false);
      MeshCtrlObj.SourceGeometry = sm;

      MeshCtrlObj.SweepShape = 2;
      MeshCtrlObj.SweepBiasType = 3;
      MeshCtrlObj.SweepBiasValue = 1.0;
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      str1 = String(arrLowerAndValve[j].Name);
      str1 = str1.substring(6, str1.length); //remove fluid-
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + str1 + ")";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  if (topoArr1.length) {
    sm.Clear();
    for (j = 0; j < topoArr1.length; ++j) {
      sm.AddToSelection(partArr1[j], topoArr1[j], false);
    }
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);  // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.ESize = ChSize/*meshSize*/; // specify your size specifycation
      MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (ch-sweep-source)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }

  //# piston-bowl top face(intf-piston-bowl) should be given hard sizing RefSize
  if (intfBowl) {
    ns = intfBowl;
    sm.Clear();
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      curPartId = str1.substring(0, pos);
      topid = str1.substring(pos + 1);
      sm.AddToSelection(curPartId, topid, false);
    }
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);  // 26 is for SizeControl
    if (MeshCtrlObj) {
      MeshCtrlObj.ESize = ChSize/*meshSize*/; // specify your size specifycation
      MeshCtrlObj.SizingType = 1; //Hard
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (intf-piston-ch)";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }

  //Create VC
  for (j = 0; j < arrIntfForVC.length; ++j) {
    ns = arrIntfForVC[j];
    topoArr = new Array();
    partArr = new Array();
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      partArr.push(parseInt(partid));
      topid = str1.substring(pos + 1);
      topoArr.push(parseInt(topid))
    }
    if (topoArr.length <= 1) continue;
    ICCreateVirtualCellForNS(ns, topoArr, partArr);
  }
  ICECreateVirtualEdges(1,0);

  //Sizing for ch-lower edges
  if (intfDeck && arrIntfChLower.length) {
    sm.Clear();
    var deckEdges = new Array();
    var valveEdges = new Array();
    ns = intfDeck;
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      topid = str1.substring(pos + 1);
      part = Assy.PartById(partid);
      face = part.BRep.Cell(topid);
      var edges = face.Edges;
      for (j = 1; j <= edges.Count; ++j) {
        deckEdges.push((edges.item(j)).Id);
      }
    }
    for (k = 0; k < arrIntfChLower.length; ++k) {
      ns = arrIntfChLower[k];
      if (ns.NumInSelection - ns.NumSuppressedItems <= 0) continue;
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        part = Assy.PartById(partid);
        face = part.BRep.Cell(topid);
        var edges = face.Edges;
        for (j = 1; j <= edges.Count; ++j) {
          valveEdges.push((edges.item(j)).Id);
        }
      }
    }

    for (k = 0; k < deckEdges.length; ++k) {
//      for (j = 0; j < valveEdges.length; ++j) {
//        if (deckEdges[k] == valveEdges[j])
//          break;
//      }
//      if(j < valveEdges.length)
        sm.AddToSelection(partid, deckEdges[k], false);
    }
    if (sm.SelectedCount) {
      //Body sizing
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        MeshCtrlObj.ESize = IntfVlayerCh/*meshSize / 2.0*/; // specify your size specifycation
        MeshCtrlObj.SizingType = 1; //Hard
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (intf-ch-lower)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }
  }  
    
}

function getBodyName(partId, bodyId) {
  var i, j, protoGroup, childList, proto, child, protoList;
  var bodies, body, name;

  protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  childList = protoGroup.Children;

  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);
    protoList = child.Prototypes;
    if (!protoList.Count)
      continue;
    proto = protoList.item(1);
    if (partId != proto.Part.Id)
      continue;
    bodies = proto.Part.BRep.Bodies
    for (j = 1; j <= bodies.Count; j++) {
      body = bodies.item(j);
      if (body.Id == bodyId)
        break;
    }
    if (j > protoList.Count)
      break;
    proto = protoList.item(j);
    name = proto.Name;
    break;
  }
  return name;
}
function suppressExistingControls() {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl, str1;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    meshctrl.SubValue = false;
  }
}
function checkPortsIfAnyVCIsCausingError() {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var MessageDatabase = ds.Tree.MessageDatabase;
  var nb = MessageDatabase.NumMessages;
  var needtoremesh=false;
  for (var i = 0; i < nb; ++i) {
    var msgObj = MessageDatabase.GetMessage(i);
    if (msgObj == null)
      continue;
    var numTopos;
    numTopos = msgObj.NumTopoId();
    if (0 == numTopos)
      continue;
    var part = Assy.PartById(msgObj.GetPartId(0));
    var str = String(part.Name);
    if (str.indexOf("-port-") == -1) continue;
    str = String(msgObj.DisplayString);
    if (str.indexOf("The following surfaces cannot be meshed with acceptable quality. Try using a different element size or virtual topology.") != 0)
      continue;

    sm.Clear();
    var oldPart;
    for (var j = 0; j < numTopos; j++) {
      var partId = msgObj.GetPartId(j);
      var topoId = msgObj.GetTopoId(j);
      sm.AddToSelection(partId, topoId, false);
      DeleteVCAndUpdateNS(partId, topoId);
      needtoremesh = true;
    }
  }
  return needtoremesh;
}
function DeleteVCAndUpdateNS(partId, topoId) {
  var branch = ds.Tree.FirstActiveBranch;
  var VCellGroup = branch.VirtualCellGroup;
  var vCells = VCellGroup.VirtualCells;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var trgVC = null;

  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  for (var i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    part = Assy.PartById(vCell.PartId);
    if (partId != vCell.PartId) continue;
    if (part.GetTopoId(vCell.RefId) == topoId) {
      trgVC = vCell;
      break;
    }
  }
  for (var i = 0; i < 1; ++i) {
    if (!trgVC) break;
    vCell = trgVC;
    var part = Assy.PartById(vCell.PartId);
    var facesNew = part.BRep.Cells(2);
    //if (vCell.Suppressed) continue;
    if (vCell.VTClass != 2) continue; //only faces
    vCell.Suppressed = true;

    var facesOld = part.BRep.Cells(2);
    var faceArr = new Array();
    var id, j, k;
    for (j = 1; j <= facesOld.Count; ++j) {
      id = facesOld.item(j).Id;
      for (k = 1; k <= facesNew.Count; ++k) {
        if (!facesNew.item(k)) continue; //face got deleted
        if (id == facesNew.item(k).Id)
          break;
      }
      if (k > facesNew.Count)
        faceArr.push(id);
    }
    if (!faceArr.length) continue;
    vCell.Suppressed = false;

    found = 0;
    var ns;
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(k));
        pos = str1.indexOf(";");
        partId = str1.substring(0, pos);
        if (partId != part.Id)
          break;
        var topoId1 = str1.substring(pos + 1);
        if (topoId1 == topoId) {
          found = j;
          break;
        }
      }
      if (found) break;
    }
    VCellGroup.DeleteVCellAndDependents(vCell.ID);

    if (!found) break;

    sm.Clear();
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      pos = str1.indexOf(";");
      partId = str1.substring(0, pos);
      var topoId1 = str1.substring(pos + 1);
      sm.AddToSelection(partId, topoId1, false);
    }
    for (var k = 0; k < faceArr.length; ++k) {
      sm.AddToSelection(partId, faceArr[k], false);
    }
    ns.GeometrySelection = sm;

    //Update the inflation
    found = false;
    sm.Clear();
    var port;
    arr = new Array();
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str1 = String(ns.Name);
      str2 = str1.substring(0, 7);
      if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-port") != -1)) {
        arr.push(ns);
      }
    }

    //Sweep for bottom ports.
    var pos, partid, partIdInt, part;
    var attrs, attr;
    var face/*IABrFace*/, edges, edge, body, bodies, faces;
    var partArr, bodiesArr;
    partArr = new Array();
    bodiesArr = new Array();

    for (j = 1; j <= nsl.Count; j++) {
      var ns = nsl.item(j);
      var str1 = String(ns.Name);
      var str2 = str1.substring(0, 7);
      if ((str2.indexOf("fluid-") == -1) || (str1.indexOf("-port") == -1))
        continue;
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        break;
      }
      partIdInt = parseInt(partid);
      part = Assy.PartById(partIdInt);
      attrs = part.AttributesByName(1,"ICEngine_SweepSources");
      for (i = 1; i <= attrs.Count; ++i) {
        attr = attrs.item(i);
        face = part.BRep.Cell(attr.TopoId);
        bodies = face.Bodies;
        if (bodies.Count == 2) {
          partArr.push(partIdInt);
          bodiesArr.push(bodies.item(1));
          bodiesArr.push(bodies.item(2));
        }
      }
    }
    sm.Clear();
    found = false;
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str1 = String(ns.Name);
      if ((str1.indexOf("port") != -1 && str1.indexOf("fluid-") == -1)) {
        found = true;
        for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
          str1 = String(ns.GetUnsuppressedPartTopoPair(i));
          var pos = str1.indexOf(";");
          var partid = str1.substring(0, pos);
          var topid = str1.substring(pos + 1);
          partIdInt = parseInt(partid);
          part = Assy.PartById(partIdInt);
          face = part.BRep.Cell(topid);
          bodies = face.Bodies;
          if (bodies.Count != 1) continue;
          body = bodies.item(1);
          for (k = 0; k < partArr.length; ++k) {
            if (partArr[k] != partIdInt) continue;
            if (bodiesArr[2 * k].Id == body.Id || bodiesArr[2 * k + 1].Id == body.Id)
              break;
          }
          if (k < partArr.length) continue;
          sm.AddToSelection(partid, topid, false);
        }
      }
    }

    if (!found) continue;
    var meshGroup = branch.MeshControlGroup;
    var mehctrls = meshGroup.MeshControls;
    for (j = 1; j <= mehctrls.Count; j++) {
      var meshctrl = mehctrls.item(j);
      str1 = new String(meshctrl.Name);
      if ((str1.indexOf("port") == -1))
        continue;
      if (meshctrl.ControlType == ds.Script.id_Inflation) {
        meshctrl.SourceGeometry = sm;
        break;
      }
    }

    break;
  }
}
function RemoveUserNSfromDefaultNS() {
  var branch = ds.Tree.FirstActiveBranch;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var i, j, k, l, ns, str, str1, pos, partId, topoId;

  for (i = 1; i <= nsl.Count; ++i) {
    ns = nsl.item(i);
    str = ns.Name;
    if (str.indexOf("ice-user-") != 0) continue;
    if ( (ns.NumInSelection - ns.NumSuppressedItems) <= 0) continue;
    str1 = String(ns.GetUnsuppressedPartTopoPair(0));
    pos = str1.indexOf(";");
    var curPartId = str1.substring(0, pos);
    var curTopoArr = new Array();
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      pos = str1.indexOf(";");
      partId = str1.substring(0, pos);
      if (curPartId != partId) continue;
      topoId = str1.substring(pos + 1);
      curTopoArr.push(topoId);
    }

    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str = ns.Name;
      if (str.indexOf("ice-user-") == 0) continue;
      var modTopoArr = new Array();
      for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(k));
        pos = str1.indexOf(";");
        partId = str1.substring(0, pos);
        if (curPartId != partId) break;
        topoId = str1.substring(pos + 1);
        for (l = 0; l < curTopoArr.length; ++l) {
          if (topoId == curTopoArr[l]) break;
        }
        if (l == curTopoArr.length)
          modTopoArr.push(topoId);
      }
      if (curPartId != partId) continue;
      if (modTopoArr.length < (ns.NumInSelection - ns.NumSuppressedItems)) {
        sm.Clear();
        for (var k = 0; k < modTopoArr.length; ++k) {
          sm.AddToSelection(curPartId, modTopoArr[k], false);
        }
        ns.GeometrySelection = sm;
      }
    }
  }

}

function CheckIfAllTheFacesAreThereInNS() {
  var proto, child, protoList;
  var faces,bodies;

  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var childList = protoGroup.Children;

  var branch = ds.Tree.FirstActiveBranch;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var i, j, k, l, ns, str, str1, pos, partId, topoId;

  var MessageDatabase = ds.Tree.MessageDatabase;

  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);
    var partName = child.Name;
    if (partName.indexOf("ch-upper") != -1 || partName.indexOf("ch-lower") != -1 || partName.indexOf("crevice") != -1) 
      continue;
    protoList = child.Prototypes;
    if (!protoList.Count)
      continue;
    proto = protoList.item(1);
    faces = proto.Part.BRep.Cells(2);
    var facesNSArr = new Array();
    for (j = 1; j <= faces.Count; ++j)
      facesNSArr.push(0);

    var curPartId = proto.Part.Id;
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      var modTopoArr = new Array();
      for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(k));
        pos = str1.indexOf(";");
        partId = str1.substring(0, pos);
        str = ns.Name;
        if (str.indexOf("ice-") != 0) { //ice-* ns can have faces from different parts.
          if (curPartId != partId) break;
        }
        topoId = str1.substring(pos + 1);
        for (l = 1; l <= faces.Count; ++l) {
          if (topoId == faces.item(l).Id) break;
        }
        if (l <= faces.Count) {
          facesNSArr[l - 1] = j;
        }
      }
    }
    var missingTopoArr = new Array();
    var missingNSArr = new Array();
    for (j = 0; j < facesNSArr.length; j++) {
      if (!facesNSArr[j]) {
        bodies = faces.item(j + 1).Bodies;
        if (bodies.Count > 1) continue;
        if (partName.indexOf("piston-layer") != -1) {
          str = getBodyName(curPartId, bodies.item(1).Id);
          if (str.indexOf("ch") == -1)
            continue;
        }
        missingTopoArr.push(faces.item(j + 1).Id);
        for (k = j + 1; k < facesNSArr.length; ++k) {
          if (facesNSArr[k]) {
            for (l = 0; l < missingNSArr.length; ++l) {
              if (missingNSArr[l] == facesNSArr[k])
                break;
            }
            if (l == missingNSArr.length)
              missingNSArr.push(facesNSArr[k]);
            break;
          }
        }
      }
    }
    if (missingTopoArr.length) {
      MessageDatabase.AddMessageString("ICE");
      var message = MessageDatabase.GetMessage(MessageDatabase.NumMessages - 1);
      message.PathId = 14;
      message.DisplayPath = "Project>Model";
      message.FormatType = 0;

      for (j = 0; j < missingTopoArr.length; ++j) {
        message.AddTopoId(curPartId, missingTopoArr[j]);
      }
      var str="Some faces of "+partName+" does not belong to any Named Selection. They might belong to: ";
      for (j = 0; j < missingNSArr.length; ++j) {
        if(j==0)
          str = str + (nsl.item(missingNSArr[j])).Name;
        else
          str = str + " or " + (nsl.item(missingNSArr[j])).Name;
      }
      message.DisplayString = str;
      MessageDatabase.AddMessage(message);
    }

  }

}
function ICEAddMessage(msg, msgType)
{
  var MessageDatabase = ds.Tree.MessageDatabase;
  if(!MessageDatabase)
    return;
  MessageDatabase.AddMessageString("ICE");
  var message = MessageDatabase.GetMessage(MessageDatabase.NumMessages - 1);
  message.PathId = 14;
  message.DisplayPath = "Project>Model";
  if(msgType=="Warning")
    message.FormatType = 2;
  else if(msgType=="Info")
    message.FormatType = 1;
  else if(msgType=="Error")
    message.FormatType = 0;
  message.DisplayString = msg;
  MessageDatabase.AddMessage(message);
}
function SuppressSweepMethods() {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  sm.Clear();
  var i,j,k;

  for (j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var protos = meshctrl.Prototypes;
    for (i = 1; i <= protos.Count; ++i) {
      var proto = protos.item(i);
      var str = proto.Name;
      if (proto.Elements > 0)
        continue;
      if (str.indexOf("port") != -1) {
        meshctrl.SubValue = false;
        var bodies = proto.Part.BRep.Bodies;
        for(k=1; k<=bodies.Count; ++k)
          sm.AddToSelection(proto.Part.Id, bodies.item(k).Id, false);
      }
    }
  }
  if (sm.SelectedCount) {
    if (sm.SelectedCount) {
      //Create Patch dependent tet mesh otherwise quality will be bad(case5 cummins)
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
      if (MeshCtrlObj) {
        MeshCtrlObj.Value = 1;
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (port)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }    
    ICDoModelPreviewMeshBodySelection();
    sm.Clear();
  }
}
function getCA() {
  var str1, i, j, str2;
  var meshSize = 0.93;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_ValveLifts");
  var CA=0.;
  for (i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.String);
    pos = str.indexOf("CA-");
    str = str.substring(pos + 3);
    str = str.substring(0,str.length-1);
    CA = new Number(str);
  }
  return CA;
}

function getValveLifts() {
  var str1, i, j, str2;
  var meshSize = 0.93;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_ValveLifts");
  var liftArray = new Array();
  var str1;
  //attribute string will be of format "invalve1-1.6700;exvalve1-3.3700;CA-350.00;"
  for (i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.String);
    pos = str.indexOf("CA-");
    if (pos >= 0) {
      str = str.substring(0, pos);
    }
    pos = str.indexOf("-");
    while (pos >= 0) {
      str1 = str.substring(0, pos);
      liftArray.push(str1);
      str = str.substring(pos+1);
      pos = str.indexOf(";");
      str1 = str.substring(0, pos);
      liftArray.push(str1);
      str = str.substring(pos + 1);
      pos = str.indexOf("-");
    }
    break;
  }
  return liftArray;
}
function createIBVirtualEdgeSplits() {
  var i, j, k;
  var topid, partid;
  var edgeArr, edgePartArr;
  var facesArr;
  var wallfaceArr, wallPartArr;
  edgesArr = new Array();
  edgePartArr = new Array();
  facesArr = new Array();
  wallfaceArr = new Array();
  wallPartArr = new Array();

  var edgesArr1 = new Array();
  var edgePartArr1 = new Array();
  
  if (!ds.Tree.FirstActiveBranch) return;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  var topBodiesArr = ICGetIBTopBodies();

  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 9);
    if ((str2.indexOf("intf-") != -1) && (str2.indexOf("intf-int-") == -1) && (str1.indexOf("-ib-fluid-ib") != -1)) {
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        part = Assy.PartById(partid);
        face = part.BRep.Cell(topid);
        var bodies = face.bodies;
        var bodyId = bodies.item(1).Id;
        for (k = 0; k < topBodiesArr.length / 2; k++) {
          if (topBodiesArr[2 * k + 1] != partid) continue;
          if (topBodiesArr[2 * k] == bodyId) break;
        }
        if (k < topBodiesArr.length / 2) continue;
        edges = face.Edges;
        facesArr.push(face);
        facesArr.push(face);
        for (k = 1; k <= edges.Count; ++k) {
          //if (edges.item(k).CurveType == 1)//Line
          if (IsEdgeALine(edges.item(k)))//Line
          {
            edgesArr.push(edges.item(k));
            edgePartArr.push(parseInt(partid));
          }
        }
        break;
      }
    }
    else if ((str2.indexOf("intf-") == -1) && (str2.indexOf("fluid-") == -1) && (str1.indexOf("-ib") != -1)) {
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        wallfaceArr.push(parseInt(topid));
        wallPartArr.push(parseInt(partid))
      }
    }
  }
  if (facesArr.length == edgesArr.length) {
    var lCommonEdge = false, length;
    var vetex, faces, edges;

    for (i = 0; i < edgesArr.length; ++i) {
      edges = facesArr[i].Edges;

      var edgeArrOri = new Array();
      var edgePartArrOri = new Array();
      for (j = 1; j <= edges.Count; ++j) {
        edgeArrOri.push(edges.item(j).Id);
        edgePartArrOri.push(edgePartArr[i]);
      }
      edge = edgesArr[i];
      length = IcGetEdgeLengthAMPUnits(edge.Id, edgePartArr[i]);
      vetex = edge.StartVertex;
      faces = vetex.Faces;
      var outerVertex = false;
      for (j = 1; j <= faces.Count; j++) {
        for (k = 0; k < wallfaceArr.length; ++k) {
          if (wallPartArr[k] == edgePartArr[i]) {
            if (wallfaceArr[k] == faces.item(j).Id)
              break;
          }
        }
        if (k < wallfaceArr.length) {
          outerVertex = true;
          break;
        }
      }
      var reverse = true;
      /*if (edge.CurveType == 1)//Line
      {
        if (edge.Curve.StartPoint.X == vetex.Point.X
              && edge.Curve.StartPoint.Y == vetex.Point.Y
              && edge.Curve.StartPoint.Z == vetex.Point.Z) {
          reverse = false;
        }
      }*/
      if (IsEdgeALine(edge))//Line
      {
        if (IcAreDoublesEqual(edge.StartVertex.Point.X, vetex.Point.X)
              && IcAreDoublesEqual(edge.StartVertex.Point.Y, vetex.Point.Y)
              && IcAreDoublesEqual(edge.StartVertex.Point.Z, vetex.Point.Z)) {
          reverse = false;
        }
      }
      

      var ratio;
      if (outerVertex)
        ratio = 0.2 / length;
      else
        ratio = 1 - (0.2 / length);
      if (reverse)
        ratio = 1 - ratio;

      sm.Clear();
      sm.AddToSelection(edgePartArr[i], edge.Id, false);
      var vcell = ICEVirtualSplitEdge();
      if (vcell) {
        vcell.SplitEdgeRatio = ratio;
        var edgesNb = new Array();
        edges = facesArr[i].Edges; //sweep source face new edges
        for (j = 1; j <= edges.Count; ++j) {
          for (k = 0; k < edgeArrOri.length; ++k) {
            if (edgePartArr[i] != edgePartArrOri[k])
              continue;
            if (edges.item(j).Id == edgeArrOri[k])
              break;
          }
          if (k == edgeArrOri.length)
            edgesNb.push(j);
        }
        if (edgesNb.length == 2) {
          if (edges.item(edgesNb[0]).Length > edges.item(edgesNb[1]).Length) {
            edgesArr1.push(edges.item(edgesNb[1]).Id);
          }
          else {
            edgesArr1.push(edges.item(edgesNb[0]).Id);
          }
          edgePartArr1.push(edgePartArr[i]);
        }
      }
    }
  }

  edgesArr1 = edgesArr1.concat(edgePartArr1);
  return edgesArr1;
}
function IsEdgeALine(edge){
  var startV = edge.StartVertex;
  var x1 = startV.Point.X;
  var y1 = startV.Point.Y;
  var z1 = startV.Point.Z;
  var endV = edge.EndVertex;
  var x2 = endV.Point.X;
  var y2 = endV.Point.Y;
  var z2 = endV.Point.Z;
  var len = Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));
  var diff = Math.abs(1 - (len / edge.Length));
  if (diff < 0.001)
    return 1;
  else
    return 0;
}
function DefineOrResetChamberInflation() {
  var i, j, k, l, str1;
  var nsl, ns;
  var Assys, Assy;
  var ns, name, found;
  var partid, topid, pos;
  var faces, Part, body, face;
  var arr, arrch;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //Chcking keygrid attr
  var keygrid;
  keygrid = ICGetKeyGrid();
 
  //finding chamber inflation controls-------
  var mehctrls = meshGroup.MeshControls;
  var MeshCtrlObjInfl = null
  for (i = 1; i <= mehctrls.Count; i++) {
    meshctrl = mehctrls.item(i);
    var str1 = new String(meshctrl.Name);
    if ((str1.indexOf("(ch)") != -1)) {
      if (meshctrl.ControlType == ds.Script.id_Inflation) {
        MeshCtrlObjInfl = meshctrl;
        break;
      }
    }
  }

  //Chcking keygrid attr
  if (keygrid == 0) {
    if (MeshCtrlObjInfl) {
      if (MeshCtrlObjInfl.SubValue)
        MeshCtrlObjInfl.SubValue = false;
    }
    return;
  }
 
  //Finding ch body
  var protoch;
  var BodychTopId = 0, BodychPartId = 0;
  sm.Clear();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("fluid-ch") != -1) && (str1.indexOf("fluid-ch-") == -1)) {
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        Part = Assy.PartById(parseInt(partid));
        BodychTopId = topid;
        BodychPartId = partid;
        sm.AddToSelection(partid, topid, false);
      }
      break;
    }
  }
  

  
  //------------------------------------
  //Creat or reset inflation control
  if (sm.SelectedCount) {
    if (!MeshCtrlObjInfl) {
      MeshCtrlObjInfl = meshGroup.AddMeshControl(sm, ds.Script.id_Inflation);
      if (MeshCtrlObjInfl) {
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObjInfl.Name = MeshCtrlObjInfl.Name + " (ch)"
        ds.Script.addNodeAndChildren(MeshCtrlObjInfl, MeshCtrlGrpNode);
      }
    }
    else {
      str1 = MeshCtrlObjInfl.Name;
      MeshCtrlObjInfl.GeometrySelection = sm;
      MeshCtrlObjInfl.Name = str1;
    }
  }
 
 //----------------------------------------
  //Finding layer cylinder
  sm.Clear();
  var bodies, protoGroup, childList, child, protoList, proto, m, n, pistonType3;
  pistonType3 = 1;
  protoGroup = ICGetProtoGroup();
  childList = protoGroup.Children;
  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    str1 = String(child.Name);
    if (str1.indexOf("piston-layer") == -1)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      proto = protoList.item(j);
      str1 = String(proto.Name);
      if (str1.indexOf("layer-cylinder") != -1) {
        sm.Clear();
        pistonType3 = 0;
        protolc = proto;
        bodies = protolc.Part.BRep.Bodies;
      }
    }
  }
  
  //---------------
  //Reset chamber inflation supports
  if (MeshCtrlObjInfl) {
    var bodies = Part.BRep.Bodies;
    for (i = 1; i <= bodies.Count; i++) {
      body = bodies.item(i);
      if (body.Id == BodychTopId) {
        break;
      }
    }
    faces = body.Faces;
    if (sm.SelectedCount) {
      str1 = MeshCtrlObjInfl.Name;
      MeshCtrlObjInfl.GeometrySelection = sm;
      MeshCtrlObjInfl.Name = str1;
    }
    arrch = new Array();
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str1 = String(ns.Name);
      if ((str1.indexOf("int-piston") != -1) || (str1.indexOf("symm-cyl-tri") != -1)) {
        arrch.push(ns);
      }
    }
    sm.Clear();
    var flag = 1;
    for (k = 1; k <= faces.Count; k++) {
      flag = 1;
      face = faces.item(k);
      for (j = 0; j < arrch.length; j++) {
        ns = arrch[j];
        for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
          str1 = String(ns.GetUnsuppressedPartTopoPair(i));
          var pos = str1.indexOf(";");
          var partid = str1.substring(0, pos);
          var topid = str1.substring(pos + 1);
          if (face.Id == topid) {
            flag = 0;
          }
          //sm.AddToSelection(partid, topid, false);
        }
      }
      if (flag) {
        sm.AddToSelection(partid, face.Id, false);
      }
    }

    if (MeshCtrlObjInfl) {
      MeshCtrlObjInfl.SourceGeometry = sm;
    }
  }
  //----------
  var Tolerence;
  if (MeshCtrlObjInfl) {
    var Tolerence = ICGetValveOpeningTolerence();
    if ((!pistonType3) && (Tolerence >= 3)) {
      if (!MeshCtrlObjInfl.SubValue)
        MeshCtrlObjInfl.SubValue = true;
    }
    else {
      if (MeshCtrlObjInfl.SubValue)
        MeshCtrlObjInfl.SubValue = false;
    }
  }
  //-----------------
}
function ResetPortSweepCntrl() {

  var i, j, k, l, str1;
  var nsl, ns;
  var found;
  var Assys, Assy;
  var ns, name, found, intPistonNs = 0;
  var partid, topid, pos;

  
  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);


  //Finding geoemetry

  sm.Clear();
  var port;
  arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-port") != -1)) {
      arr.push(ns);
    }
  }


  //Sweep for bottom ports.
  var pos, partid, partIdInt, part;
  var attrs, attr;
  var face/*IABrFace*/, edges, edge, body, bodies, faces;
  var facesArr, partArr, bodiesArr, wallfaceArr, wallPartArr, wallNSArr;
  facesArr = new Array();
  partArr = new Array();
  bodiesArr = new Array();
  
  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      break;
    }
    partIdInt = parseInt(partid);
    part = Assy.PartById(partIdInt);
    attrs = part.AttributesByName(1,"ICEngine_SweepSources");
    for (i = 1; i <= attrs.Count; ++i) {
      attr = attrs.item(i);
      face = part.BRep.Cell(attr.TopoId);
      bodies = face.Bodies;
      if (bodies.Count == 2) {
        facesArr.push(face);
        partArr.push(partIdInt);
        bodiesArr.push(bodies.item(1));
        bodiesArr.push(bodies.item(2));
      }
    }
  }


  // Do not set the sweep method if the bodies are not sweepable
  sm.Clear();
  meshGroup.PreviewSweepable(sm);
  var partId, sweepArr;
  sweepArr = new Array();
  var facesArrTmp = new Array();
  var partArrTmp = new Array();
  var bodiesArrTmp = new Array();
  for (i = 1; i <= sm.SelectedCount; i++) {
    sweepArr.push(sm.SelectedPartID(i));
  }
  for (i = 0; i < facesArr.length; ++i) {
    for (j = 0; j < sweepArr.length; ++j) {
      if (sweepArr[j] == partArr[i])
        break;
    }
    if (j < sweepArr.length) {
      facesArrTmp.push(facesArr[i]);
      partArrTmp.push(partArr[i]);
      bodiesArrTmp.push(bodiesArr[2 * i]);
      bodiesArrTmp.push(bodiesArr[2 * i + 1]);
    }
  }
  if (facesArrTmp.length == 0) return;

  facesArr = facesArrTmp;
  partArr = partArrTmp;
  bodiesArr = bodiesArrTmp;
  
  
  //3 Sweep for bottom ports & Hard sizing for source faces
  //========================================

  var mehctrls = meshGroup.MeshControls;
  var meshctrlSwp = null;
  var meshctrlSize = null;
  
  for (i = 0; i < facesArr.length; i++) {

    //Find control
    str = Assy.PartById(partArr[i]).Name;
    str = getBodyName(partArr[i], bodiesArr[2 * i].Id);
    str = str.substring(0, str.length - 5); //remove -body
    //------------------

    meshctrlSwp = null;
    meshctrlSize = null;
    meshctrl = null;
    for (j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      var str1 = new String(meshctrl.Name);
      if ((str1.indexOf(str) != -1)) {
        if (meshctrl.ControlType == ds.Script.id_BodyMeshType)
          meshctrlSwp = meshctrl;
        else if (meshctrl.ControlType == ds.Script.id_Size)
          meshctrlSize = meshctrl;
      }
    }

    if (meshctrlSwp) {
      sm.Clear();
      sm.AddToSelection(partArr[i], bodiesArr[2 * i].Id, false);
      sm.AddToSelection(partArr[i], bodiesArr[2 * i + 1].Id, false);

      if (sm.SelectedCount) {
        str1 = meshctrlSwp.Name;
        meshctrlSwp.GeometrySelection = sm;
        meshctrlSwp.Name = str1;
      }

      //Source geometry
      sm.Clear();
      sm.AddToSelection(partArr[i], facesArr[i].Id, false);
      meshctrlSwp.SourceGeometry = sm;
    }

    if (meshctrlSize) {
      sm.AddToSelection(partArr[i], facesArr[i].Id, false);
      if (sm.SelectedCount) {
        str1 = meshctrlSize.Name;
        meshctrlSize.GeometrySelection = sm;
        meshctrlSize.Name = str1;
      }
    }
  }
  
}
function ResetChamberCntrls() {
  
  var i, j, k, l, str1;
  var nsl, ns;
  var found;
  var Assys, Assy;
  var ns, name, found, intPistonNs = 0;
  var partid, topid, pos;

  
  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;

  //finding chamber controls-------
  var mehctrls = meshGroup.MeshControls;
  var meshctrlSwp = null, meshctrlSize = null, meshctrlSizeCh = null, meshctrlpiston = null, meshctrlpiston2 = null;
  for (i = 1; i <= mehctrls.Count; i++) {
    meshctrl = mehctrls.item(i);
    var str1 = new String(meshctrl.Name);
    if ((str1.indexOf("layer-cylinder") != -1)) {
      if (meshctrl.ControlType == ds.Script.id_BodyMeshType)
        meshctrlSwp = meshctrl;
      else if (meshctrl.ControlType == ds.Script.id_Size)
        meshctrlSize = meshctrl;
    }
    else if ((str1.indexOf("(piston)") != -1)) {
      if (meshctrl.ControlType == ds.Script.id_Size) {
        meshctrlpiston = meshctrl;
        if (i < mehctrls.Count) {
          meshctrl = mehctrls.item(i + 1);
          if((meshctrl.ControlType == ds.Script.id_BodyMeshType)&&(meshctrl.Value == 1))
            meshctrlpiston2 = meshctrl
        }
      }
    }
    if ((str1.indexOf("(ch)") != -1)) {
    if (meshctrl.ControlType == ds.Script.id_Size)
      meshctrlSizeCh = meshctrl;
    }
  }

  //Reset ch body sizing
  var protoch;
  if (meshctrlSizeCh) {
    sm.Clear();
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str1 = String(ns.Name);
      str2 = str1.substring(0, 7);
      if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("fluid-ch") != -1) && (str1.indexOf("fluid-ch-") == -1)) {
        for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
          str1 = String(ns.GetUnsuppressedPartTopoPair(i));
          pos = str1.indexOf(";");
          partid = str1.substring(0, pos);
          topid = str1.substring(pos + 1);
          sm.AddToSelection(partid, topid, false);
        }
        break;
      }
    }
    if (sm.SelectedCount) {
      str1 = meshctrlSizeCh.Name;
      meshctrlSizeCh.GeometrySelection = sm;
      meshctrlSizeCh.Name = str1;
    }
  }
  //----

  //finding layer cylinder-------
  sm.Clear();
  var bodies, protoGroup, childList, child, protoList, proto,m,n,flag;
  var pistonBody = -1, partId = 0;
  flag = 0;
  protoGroup = ICGetProtoGroup();
  childList = protoGroup.Children;
  for (i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    str1 = String(child.Name);
    if ((str1.indexOf("piston-layer") == -1) && (str1.indexOf("Single-Zone") == -1))
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      proto = protoList.item(j);
      str1 = String(proto.Name);
      if (str1.indexOf("layer-cylinder") != -1) {
        flag = 1;
        protolc = proto;
        bodies = protolc.Part.BRep.Bodies;
        sm.AddToSelection(protolc.Part.Id, bodies.item(j).Id, false);
      }
      if (str1.indexOf("piston") != -1) {
        bodies = proto.Part.BRep.Bodies;
        pistonBody = bodies.item(j).Id;
        partId = proto.Part.Id;
      }
    }
  }

//Assigning bodies to layer cylinder control
  if (meshctrlSwp && meshctrlSize && meshctrlpiston) {
      meshctrlSwp.GeometrySelection = sm;
      str1 = meshctrlSwp.Name;
      if (str1.indexOf("layer-cylinder") == -1)
       meshctrlSwp.Name = meshctrlSwp.Name + " (layer-cylinder)"; 
      meshctrlSize.GeometrySelection = sm;
      str1 = meshctrlSize.Name;
      if (str1.indexOf("layer-cylinder") == -1)
       meshctrlSize.Name = meshctrlSize.Name + " (layer-cylinder)";

     if (pistonBody > -1) {
       sm.Clear();
       sm.AddToSelection(partId, pistonBody, false);
       meshctrlpiston.GeometrySelection = sm;
       str1 = meshctrlpiston.Name;
       if (str1.indexOf("piston") == -1)
         meshctrlpiston.Name = meshctrlpiston.Name + " (piston)";

       if(meshctrlpiston2 && (meshctrlpiston2.GeometryNum != sm.SelectedCount))
         meshctrlpiston2.GeometrySelection = sm;
     }
     
    if (flag) {
      if (!meshctrlSwp.SubValue)
        meshctrlSwp.SubValue = true;
      if (!meshctrlSize.SubValue)
        meshctrlSize.SubValue = true;
      if (!meshctrlpiston.SubValue)
        meshctrlpiston.SubValue = true;
      if (meshctrlpiston2 && !meshctrlpiston2.SubValue)
        meshctrlpiston2.SubValue = true;
    }
    else {
      if (meshctrlSwp.SubValue)
        meshctrlSwp.SubValue = false;
      if (meshctrlSize.SubValue)
        meshctrlSize.SubValue = false;
      if (meshctrlpiston.SubValue)
        meshctrlpiston.SubValue = false;
      if (meshctrlpiston2 && meshctrlpiston2.SubValue)
        meshctrlpiston2.SubValue = false;
    }
  }

  //Reset 'intf-vlayer-ch' control
  ICDefineOrResetVlayerChSizing();

  ICDefineOrResetVlayerChEdgeSizing();
  
  IceSetValveBottomSizing();
  
  //----------------
  DefineOrResetChamberInflation();
  //-------------------
}
function ResetChLowerEdges(){
  var i, j, k, l, str1,str2;
  var nsl, ns;
  var meshGroup;
  var Assys, Assy;
  var partid, topid, pos;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  var arrIntfChLower = new Array();
  var intfDeck = null;
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 5);
    if ((str2.indexOf("intf") != -1) && (str1.indexOf("-ob-fluid-ch-lower") != -1))
      arrIntfChLower.push(ns);
    else if (str1.indexOf("intf-deck-fluid-ch-lower") != -1)
      intfDeck = ns;
  }

  //Sizing for ch-lower edges
  if (intfDeck && arrIntfChLower.length) {
    var deckEdges = new Array();
    var valveEdges = new Array();
    var chLowerEdges = new Array();

    ns = intfDeck;
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      topid = str1.substring(pos + 1);
      part = Assy.PartById(partid);
      face = part.BRep.Cell(topid);
      var edges = face.Edges;
      for (j = 1; j <= edges.Count; ++j) {
        deckEdges.push((edges.item(j)).Id);
      }
    }
    for (k = 0; k < arrIntfChLower.length; ++k) {
      ns = arrIntfChLower[k];
      if (ns.NumInSelection - ns.NumSuppressedItems <= 0) continue;
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        part = Assy.PartById(partid);
        face = part.BRep.Cell(topid);
        var edges = face.Edges;
        for (j = 1; j <= edges.Count; ++j) {
          valveEdges.push((edges.item(j)).Id);
        }
      }
    }

    for (k = 0; k < deckEdges.length; ++k) {
      for (j = 0; j < valveEdges.length; ++j) {
        if (deckEdges[k] == valveEdges[j])
          break;
      }
      if (j < valveEdges.length)
        chLowerEdges.push(deckEdges[k]);
    }
    
    var mehctrls = meshGroup.MeshControls;
    var meshctrlSize=null,meshctrl=null;
    for (i = 1; i <= mehctrls.Count; i++) {
      meshctrl = mehctrls.item(i);
      if (meshctrl.ControlType != ds.Script.id_Size)
        continue;
      var str1 = new String(meshctrl.Name);
      if ((str1.indexOf("intf-ch-lower") != -1)) {
        meshctrlSize = meshctrl;
        break;
      }
    }
    if (!meshctrlSize) return;

    if (meshctrlSize.GeometryNum < chLowerEdges.length) {
      sm.Clear();
      for (i = 0; i < chLowerEdges.length; ++i)
        sm.AddToSelection(partid, chLowerEdges[i], false);
      str1 = meshctrlSize.Name;
      meshctrlSize.GeometrySelection = sm;
      meshctrlSize.Name = str1; //Name is getting lost after setting supports.
    }
  }  
}
//=======================================================================
//Combustion
//=======================================================================
function IsCombustion() {
  var retrn = -1; // -1 for unknown, 0 for non-ic case, 1 for ic case.
  var Assys = pm.assemblies;
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_Combustion");
    if (attrs.Count)
      retrn = 1;
    else
      retrn = 0;
  }
  return retrn;
}
/*
function ICGetCombustionType() {
  var Assys = pm.assemblies;
  var CombustionType = 0;
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_Combustion");
    if (attrs.Count) {
      var attr = attrs.item(1);
      var str = new String(attr.Integer);
      CombustionType = str
    }
  }
  return CombustionType;
}
*/
function DefineSectorCombMesh() {

  if (typeof (ds.Script.lv) != "undefined")
    ds.Script.lvFroceOutOfEdit();

  //Set the units to mm
 // ds.Script.doUnitsMenu(2);
  ds.UnitSystemID = 2;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  meshGroup.PhysicsPreference = 2;
  meshGroup.SolverPreference = 0;
  meshGroup.AdvancedSizeFunction = 2; //Curvature
  meshGroup.MaxSizeSF = MaxMeshSize;
  meshGroup.MaxFaceElementSize = MaxMeshSize;
  meshGroup.MinSizeSF = MinMeshSize;
  meshGroup.MeshDefeatureTol = MinMeshSize/2.0;

  meshGroup.InflationOption = 0;
  meshGroup.MaximumThickness = MinMeshSize;
  meshGroup.NumLayers= NbInflation;

  CreateVCForPiston();
  ICUpdateNSWithVC();
  DefinePistonSweepMesh();
  DefineSquishSweepMesh(0);
  DefinePistonCoreSweepMesh();
  DefinePistonInlfationSweepMesh();
  DefineChamberTopSweepMesh();
  DefineFaceSizingPistonOuter()
  DefineFaceSizingPistonInflation();
  DefineCreviceSizingSector();
  DefineEdgeSizingPistonInflation();
  DefineInflaitonforSector();
  DefineEdgeSizingChamber();
  DefinePistonInflationEdgeSizing();

  CreateMeshingOrderSectorComb();
  
  //getNSList(1);
}
function CreateVCForPiston() {
  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var i, j;
  var partId;

  
  var Assys = pm.assemblies;
  if (Assys.Count < 1)
    return;

  var Assy = Assys.Item(1);

  var arrName = new Array();
  var arrBody = new Array();
  var arrPart = new Array();

  var MeshCtrlGrpNode;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      arrPart.push(proto.Part.Id);
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }

  var bodyreq = 0, bodyName, bodyPartID;
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if (str1.indexOf("Piston-Inflation") != -1) {
      bodyName = str1;
      bodyreq = arrBody[i];
      bodyPartID = arrPart[i];
      break;
    }
  }

  //Creating virtual face
  var faceArrpiston = new Array();
  var facePartArrpiston = new Array();
  var faceArrpistonInt = new Array();
  var facePartArrpistonInt = new Array();
  var pos;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if ((str1.indexOf("ice-piston") != -1)) {
      for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        faceArrpiston.push(topid);
        facePartArrpiston.push(partid);
      }
}
if (str1.indexOf("intf_inner_piston") != -1) {
    for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        faceArrpistonInt.push(topid);
        facePartArrpistonInt.push(partid);
    }
}
}


var part, face
if (faceArrpistonInt.length > 1) {
    sm.Clear();
    for (var i = 0; i < faceArrpistonInt.length; ++i) {
        part = Assy.PartById(facePartArrpistonInt[i]);
        face = part.BRep.Cell(faceArrpistonInt[i]);

        if (facePartArrpistonInt[i] != bodyPartID)
            continue;

        var bodies = face.Bodies;
       if (bodies.Count == 2) {
            if ((bodies.item(1).Id == bodyreq) || (bodies.item(2).Id == bodyreq))
                sm.AddToSelection(bodyPartID, face.Id, false);
        }
    }

    if (sm.SelectedCount > 1) {
        ICEAddVirtualFace();
    }
}

if (faceArrpiston.length > 1) {
    sm.Clear();
    for (var i = 0; i < faceArrpiston.length; ++i) {
        part = Assy.PartById(facePartArrpiston[i]);
        face = part.BRep.Cell(faceArrpiston[i]);

        if (facePartArrpiston[i] != bodyPartID)
            continue;

        var bodies = face.Bodies;
        if (bodies.Count == 1) {
            if (bodies.item(1).Id == bodyreq)
                sm.AddToSelection(bodyPartID, face.Id, false);
        }
        
    }

    if (sm.SelectedCount > 1) {
        ICEAddVirtualFace();
    }
}
}
function getChmaberBottomMeshSize() {
  var str1, i, j, str2;
  var lChamberBottomMeshSize = 0.93;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var Parts = Assy.Parts(true);
  var k, Part;

  var attrs = Assy.AttributesByName(1,"ICEngine_ChBotMeshSize");
  if (attrs.Count) {
    for (j = 1; j <= attrs.Count; ++j) {
      var attr = attrs.item(j);
      lChamberBottomMeshSize = attr.Double;
      break;
    }
  }
  return lChamberBottomMeshSize;
}

function  DefineSquishSweepMesh(IsRegen) {

  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var i, j;
  var partId;
  
  
  var Assys = pm.assemblies;
  if (Assys.Count < 1)
    return;

  var Assy = Assys.Item(1);

  var arrName = new Array();
  var arrBody = new Array();
  var arrPart = new Array();

  var MeshCtrlGrpNode;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      arrPart.push(proto.Part.Id);
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }

  sm.Clear();
  var bodyreq = -1, bodyName, bodyPartID;
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if ((str1.indexOf("Chamber-Outer-Bottom") != -1) || (str1.indexOf("Chamber-Inner-Bottom") != -1)) {
      bodyName = str1;
      bodyreq = arrBody[i];
      bodyPartID = arrPart[i];
      sm.AddToSelection(bodyPartID, bodyreq, false);
    }
}
  if (bodyreq<0) return;
  

  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  var MeshCtrlObj = null; 
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("Chamber-Bottom") == -1) continue;
    MeshCtrlObj = meshctrl;
  }

  if (!MeshCtrlObj) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 5;
      MeshCtrlObj.SourceTargetSelection = 1;
      MeshCtrlObj.SweepESizeType = 0;
      
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (Chamber-Bottom)";
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  else {
    var str1 = MeshCtrlObj.Name;
    MeshCtrlObj.GeometrySelection = sm;
    MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
  }
  if (!IsRegen){
    MeshCtrlObj.ESize = RefSize*3/4;
  }
  
  
 
  var pos;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  sm.Clear();
  var part, face
  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if (str1.indexOf("ice-int-chamber-piston") != -1) {
      for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        part = Assy.PartById(partid);
        face = part.BRep.Cell(topid);
        sm.AddToSelection(partid, face.Id, false);
      }
    }
  }


  if ((sm.SelectedCount) && (MeshCtrlObj)) {
    MeshCtrlObj.SourceGeometry = sm;
  }

}
function DefineChamberTopSweepMesh() {
  
    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;

    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
        }
    }

    sm.Clear();
    var bodyreq = -1, bodyName, bodyPartID;
    for (i = 0; i < arrName.length; ++i) {
        str1 = arrName[i];
        if ((str1.indexOf("Chamber-Outer-Top") != -1) || (str1.indexOf("Chamber-Inner-Top") != -1)) {
            bodyName = str1;
            bodyreq = arrBody[i];
            bodyPartID = arrPart[i];
            sm.AddToSelection(bodyPartID, bodyreq, false);
        }
    }
    if(bodyreq<0) return;
	 if (sm.SelectedCount){

    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj = null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("Chamber-Top") == -1) continue;
        MeshCtrlObj = meshctrl;
    }

    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
        if (MeshCtrlObj) {
            MeshCtrlObj.Value = 5;
            MeshCtrlObj.SweepBiasValue = 2;
            MeshCtrlObj.SweepBiasType = 0;
            MeshCtrlObj.NDiv = 3;
            MeshCtrlObj.SourceTargetSelection = 1;
            MeshCtrlObj.Name = MeshCtrlObj.Name + " (Chamber-Top)";
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }



    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    sm.Clear();
    var part, face
    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if (str1.indexOf("ice-int-chamber-top-bottom") != -1) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                part = Assy.PartById(partid);
                face = part.BRep.Cell(topid);
                sm.AddToSelection(partid, face.Id, false);
            }
        }
    }


    if ((sm.SelectedCount) && (MeshCtrlObj)) {
        MeshCtrlObj.SourceGeometry = sm;
    }
	}
}

function DefineInflaitonforSector() {
    
    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children, meshGroup;
    var i, j;
    var partId;
    //IsInflationOn = true;
    if (IsInflationOn==0) {
        var inflationTotalThickness; 
        inflationTotalThickness = RefSize/4;
        
        var Assys = pm.assemblies;
        if (Assys.Count < 1)
            return;

        var Assy = Assys.Item(1);

        var arrName = new Array();
        var arrBody = new Array();
        var arrPart = new Array();

        var MeshCtrlGrpNode;
        var branch = ds.Tree.FirstActiveBranch;
        if (!branch)
            return;
        meshGroup = branch.MeshControlGroup;
        if (!meshGroup)
            return;
        for (i = 1; i <= childList.Count; i++) {
            var child = childList.Item(i);
            if (ds.Script.id_BodyGroup != child.Class) continue;
            var protoList = child.Prototypes;
            if (!protoList || !protoList.count)
                continue;

            for (j = 1; j <= protoList.Count; j++) {
                var proto = protoList.item(j);
                str1 = String(proto.Name);
                sm.Clear();
                var bodies = proto.Part.BRep.Bodies;
                arrPart.push(proto.Part.Id);
                arrName.push(str1);
                arrBody.push(bodies.item(j).Id);
            }
        }

        var bodyreq = -1, bodyName, bodyPartID;
        for (i = 0; i < arrName.length; ++i) {
            str1 = arrName[i];
            if (str1.indexOf("Piston-Outer") != -1) {
                bodyName = str1;
                bodyreq = arrBody[i];
                bodyPartID = arrPart[i];
                break;
            }
        }
		if(bodyreq<0) return;
        var Assys = pm.assemblies;
        if (Assys.Count < 1)
            return;

        var Assy = Assys.Item(1);
        var partid, topid;
        meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
        if (!meshGroup) return;
        var faceArr = new Array();
        var facePartArr = new Array();
        var pos;
        var nsl = ds.Tree.FirstActiveBranch.Components;
        if (!nsl) return;

        for (var j = 1; j <= nsl.Count; ++j) {
            ns = nsl.item(j);
            str1 = String(ns.Name);
            if (str1.indexOf("ice-periodic-faces1") != -1) {
                for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                    str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                    pos = str1.indexOf(";");
                    partid = str1.substring(0, pos);
                    topid = str1.substring(pos + 1);
                    faceArr.push(topid);
                    facePartArr.push(partid);
                }
            }
        }

        var part, face
        sm.Clear();
        for (var i = 0; i < faceArr.length; ++i) {
            part = Assy.PartById(facePartArr[i]);
            face = part.BRep.Cell(faceArr[i]);

            if (facePartArr[i] != bodyPartID)
                continue;

            var bodies = face.Bodies;
            if (bodies.Count == 2)
                continue;

            if (bodies.item(1).Id == bodyreq)
                sm.AddToSelection(bodyPartID, face.Id, false);
        }

           //Inflation
        var MeshCtrlObj = null;
        var mehctrls = meshGroup.MeshControls;
        var MeshCtrlObj; 
        for (var i = 1; i <= mehctrls.Count; i++) {
          var meshctrl = mehctrls.item(i);
          str1 = new String(meshctrl.Name);
          if (!(meshctrl.ControlType == ds.Script.id_Inflation))
            continue;
        if (str1.indexOf("(Piston-Outer)") != -1)
            MeshCtrlObj = meshctrl;
          
        }    
        if (!MeshCtrlObj) {
            MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Inflation);
            MeshCtrlObj.Name = MeshCtrlObj.Name + " (Piston-Outer)";
            MeshCtrlObj.MaximumThickness = inflationTotalThickness;
            MeshCtrlObj.NumLayers = NbInflation;
            MeshCtrlObj.ExpansionFactor = 1.2;
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
          
         }
      else {
          if (!MeshCtrlObj.SubValue)
              MeshCtrlObj.SubValue = true;
          var str1 = MeshCtrlObj.Name;
          MeshCtrlObj.NumLayers = NbInflation;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }


      sm.Clear();

      var Parts = Assy.Parts(true);
      var k, Part, partArr, topoArr;
      partArr = new Array();
      topoArr = new Array();

      for (k = 1; k <= Parts.Count; ++k) {
          Part = Parts.Item(k);
          var attrs = Part.AttributesByName(1,"ICEngine_Piston_Inflation");
          for (j = 1; j <= attrs.Count; ++j) {
              var attr = attrs.item(j);
              var partid = Part.Id;
              var topid = attr.TopoId;
              sm.AddToSelection(partid, topid, false);
              topoArr.push(topid);
              partArr.push(partid);
          }
      }

      MeshCtrlObj.SourceGeometry = sm;
  }
  else {
    meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
    if (!meshGroup) return;
   var MeshCtrlObj = null;
    var mehctrls = meshGroup.MeshControls;
    var MeshCtrlObj; 
    for (var i = 1; i <= mehctrls.Count; i++) {
      var meshctrl = mehctrls.item(i);
      str1 = new String(meshctrl.Name);
      if (!(meshctrl.ControlType == ds.Script.id_Inflation))
        continue;
    if (str1.indexOf("(Piston-Outer)") != -1)
        MeshCtrlObj = meshctrl;
      
    }
    if (MeshCtrlObj) {
     if (MeshCtrlObj.SubValue)
          MeshCtrlObj.SubValue = false;
    
    }
    //delte virtual splits when inflation is made off
    branch = ds.Tree.FirstActiveBranch;
    
    VCellGroup = branch.VirtualCellGroup;
    if (!VCellGroup) return;
    
    vCells = VCellGroup.VirtualSplitEdges;
    if (!vCells.Count) return;
    VCellGroup.DeleteAllVirtualSplitEdges();
  
  }

}
function DefinePistonSweepMesh() {

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;

    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
        }
    }

    var bodyreq = -1, bodyName, bodyPartID;
    for (i = 0; i < arrName.length; ++i) {
        str1 = arrName[i];
        if (str1.indexOf("Piston-Outer") != -1) {
            bodyName = str1;
            bodyreq = arrBody[i];
            bodyPartID = arrPart[i];
            break;
        }
    }
    if (bodyreq < 0) return;
    sm.Clear();
    sm.AddToSelection(bodyPartID, bodyreq, false);

    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj = null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("Piston-Outer") == -1) continue;
        MeshCtrlObj = meshctrl;
    }

    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
        if (MeshCtrlObj) {
            MeshCtrlObj.Value = 5;
            MeshCtrlObj.SourceTargetSelection = 1;
            MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + bodyName + ")";
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }


    var faceArr = new Array();
    var facePartArr = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if (str1.indexOf("ice-periodic-faces1") != -1) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                faceArr.push(topid);
                facePartArr.push(partid);
            }
        }
    }

    var part, face
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
        part = Assy.PartById(facePartArr[i]);
        face = part.BRep.Cell(faceArr[i]);

        if (facePartArr[i] != bodyPartID)
            continue;

        var bodies = face.Bodies;
        if (bodies.Count == 2)
            continue;

        if (bodies.item(1).Id == bodyreq)
            sm.AddToSelection(bodyPartID, face.Id, false);
    }

    if ((sm.SelectedCount) && (MeshCtrlObj)) {
        MeshCtrlObj.SourceGeometry = sm;
    }
    

}
function DefineFaceSizingPistonInflation(){

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;
    
    var faceMeshSize; 
    faceMeshSize= RefSize/2.0; 
    


    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
        }
    }

    var bodyreq = -1, bodyName, bodyPartID;
    for (i = 0; i < arrName.length; ++i) {
        str1 = arrName[i];
        if (str1.indexOf("Piston-Inflation") != -1) {
            bodyName = str1;
            bodyreq = arrBody[i];
            bodyPartID = arrPart[i];
            break;
        }
    }
    if(bodyreq<0) return;
    var faceArr = new Array();
    var facePartArr = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if (str1.indexOf("ice-piston") != -1) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                faceArr.push(topid);
                facePartArr.push(partid);
            }
        }
    }

    var part, face
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
        part = Assy.PartById(facePartArr[i]);
        face = part.BRep.Cell(faceArr[i]);

        if (facePartArr[i] != bodyPartID)
            continue;

        var bodies = face.Bodies;
        if (bodies.Count == 2)
            continue;

        if (bodies.item(1).Id == bodyreq)
            sm.AddToSelection(bodyPartID, face.Id, false);
    }

    // defining face sizing 
    if (sm.SelectedCount) {
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("Src-PistonInflation") == -1) continue;
        MeshCtrlObj = meshctrl;
    }
    
    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
           MeshCtrlObj.Name = MeshCtrlObj.Name + "(Src-PistonInflation)";
            MeshCtrlObj.ESize = faceMeshSize;
           MeshCtrlObj.SizingType = 1; //Hard
            MeshCtrlObj.SourceTargetSelection = 1;
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.ESize = faceMeshSize;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }
   }
}

function DefineEdgeSizingPistonInflation(){

    var protoGroup = ICGetProtoGroup(),loopcount;
    var childList = protoGroup.Children;
    var i, j;
    var partId;
    
    var faceMeshSize; 
    
    faceMeshSize= RefSize/2.0; 
    


    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
       return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
        }
    }

    var bodyreq = -1, bodyName, bodyPartID;
    for (i = 0; i < arrName.length; ++i) {
        str1 = arrName[i];
        if (str1.indexOf("Piston-Inflation") != -1) {
            bodyName = str1;
            bodyreq = arrBody[i];
            bodyPartID = arrPart[i];
            break;
        }
    }
    if (bodyreq < 0) return;
    var faceArr = new Array();
    var facePartArr = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if (str1.indexOf("ice-piston") != -1) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                faceArr.push(topid);
                facePartArr.push(partid);
            }
        }
    }
    //get all edges belonging to piston face present in ice-piston NS
    var part=null, face
    var faceArr1 = new Array();
    var EdgeArr1 = new Array();
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
        part = Assy.PartById(facePartArr[i]);
        face = part.BRep.Cell(faceArr[i]);

        if (facePartArr[i] != bodyPartID)
            continue;

        var bodies = face.Bodies;
        if (bodies.Count == 2)
            continue;

        if (bodies.item(1).Id == bodyreq)
            faceArr1.push(face.Id);
    }
    if(!part) return;
    for (i = 0; i < faceArr1.length; ++i) {
      face = part.BRep.Cell(faceArr1[i]);
      edges = face.Edges;
      for (k = 1; k <= edges.Count; ++k){
        EdgeArr1.push(edges.item(k).Id);
       // sm.AddToSelection(bodyPartID, edges.item(k).Id, false);
        }
    }
    //get all edges belonging to  ice-periodic-faces1-piston NS
    var faceArrAll = new Array();
    var facePartArrAll = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if ((str1.indexOf("ice-periodic-faces1-piston") != -1) || (str1.indexOf("ice-periodic-faces2-piston") != -1)) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                faceArrAll.push(topid);
                facePartArrAll.push(partid);
            }
        }
    }
    var EdgeArrAll1 = new Array();
    for (i = 0; i < faceArrAll.length; ++i) {
      face = part.BRep.Cell(faceArrAll[i]);
      edges = face.Edges;
      for (k = 1; k <= edges.Count; ++k)
        EdgeArrAll1.push(edges.item(k).Id);
    }
    
    sm.Clear();
    loopcount = false;
    var EdgeArrReq = new Array();
    //var allEdges = part.BRep.Cells(1);
    for (var k = 0; k < EdgeArr1.length; ++k) {
       loopcount = false;
       for (var j = 0; j < EdgeArrAll1.length; ++j) {
         if (EdgeArr1[k] == EdgeArrAll1[j]){
           loopcount = true;
           break;
         }
       }
       if (!loopcount)
       sm.AddToSelection(bodyPartID, EdgeArr1[k], false);
    }

    // defining edge sizing 
    if (sm.SelectedCount) {
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("Srcedges-PistonInflation") == -1) continue;
        MeshCtrlObj = meshctrl;
    }
    
    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
           MeshCtrlObj.Name = MeshCtrlObj.Name + "(Srcedges-PistonInflation)";
            MeshCtrlObj.ESize = faceMeshSize;
           MeshCtrlObj.SizingType = 1; //Hard
            MeshCtrlObj.SourceTargetSelection = 1;
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.ESize = faceMeshSize;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }
   }
}
function DefineFaceSizingPistonOuter(){

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;
    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
        }
    }

    var bodyreq = -1, bodyName, bodyPartID;
    for (i = 0; i < arrName.length; ++i) {
        str1 = arrName[i];
        if (str1.indexOf("Piston-Outer") != -1) {
            bodyName = str1;
            bodyreq = arrBody[i];
            bodyPartID = arrPart[i];
            break;
        }
    }
    if (bodyreq < 0) return;
    var faceArr = new Array();
    var facePartArr = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
        ns = nsl.item(j);
        str1 = String(ns.Name);
        if (str1.indexOf("ice-periodic-faces1") != -1) {
            for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
                str1 = String(ns.GetUnsuppressedPartTopoPair(i));
                pos = str1.indexOf(";");
                partid = str1.substring(0, pos);
                topid = str1.substring(pos + 1);
                faceArr.push(topid);
                facePartArr.push(partid);
            }
        }
    }

    var part, face
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
        part = Assy.PartById(facePartArr[i]);
        face = part.BRep.Cell(faceArr[i]);

        if (facePartArr[i] != bodyPartID)
            continue;

        var bodies = face.Bodies;
        if (bodies.Count == 2)
            continue;

        if (bodies.item(1).Id == bodyreq)
            sm.AddToSelection(bodyPartID, face.Id, false);
    }

    // defining face sizing 
    if (sm.SelectedCount) {
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj = null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("Src-PistonOuter") == -1) continue;
        MeshCtrlObj = meshctrl;
    }
    
    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
        if (MeshCtrlObj) {
            MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
            MeshCtrlObj.Name = MeshCtrlObj.Name + "(Src-PistonOuter)";
            MeshCtrlObj.ESize = ChamberBottomMeshSize;
            //MeshCtrlObj.SizingType = 1; //Hard
            MeshCtrlObj.SourceTargetSelection = 1;
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.ESize = ChamberBottomMeshSize;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }
   }
}


function DefinePistonInlfationSweepMesh() {

  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var i, j;
  var partId;

  
  var Assys = pm.assemblies;
  if (Assys.Count < 1)
    return;

  var Assy = Assys.Item(1);

  var arrName = new Array();
  var arrBody = new Array();
  var arrPart = new Array();

  var  MeshCtrlGrpNode;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      arrPart.push(proto.Part.Id);
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }

  var bodyreq = -1, bodyName, bodyPartID;
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if (str1.indexOf("Piston-Inflation") != -1) {
      bodyName = str1;
      bodyreq = arrBody[i];
      bodyPartID = arrPart[i];
      break;
    }
  }
  if (bodyreq < 0) return;

  sm.Clear();
  sm.AddToSelection(bodyPartID, bodyreq, false);

  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  var MeshCtrlObj = null;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("Piston-Inflation") == -1) continue;
    MeshCtrlObj = meshctrl;
  }

  if (!MeshCtrlObj) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 5;
      MeshCtrlObj.SourceTargetSelection = 1;
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + bodyName + ")";
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  else {
    var str1 = MeshCtrlObj.Name;
    MeshCtrlObj.GeometrySelection = sm;
    MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
  }
  

  var faceArr = new Array();
  var facePartArr = new Array();
  var pos;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  sm.Clear();
  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if (str1.indexOf("intf_inner_piston") != -1) {
      for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        sm.AddToSelection(partid, topid, false);
      }
    }
  }


  if ((sm.SelectedCount) && (MeshCtrlObj)) {
    MeshCtrlObj.SourceGeometry = sm;
  }

}

function DefineCreviceSizingSector() {

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;

    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;

 


    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            bodyPartID = proto.Part.Id;
            break;

        }
    }


    var attrs, attr;
    var face/*IABrFace*/, edges, edge, body, bodies, faces;

    
    var part, partIdInt;
    partIdInt = parseInt(bodyPartID);
    part = Assy.PartById(partIdInt);
    sm.Clear();
    var attrs = part.AttributesByName(1,"ICEngine_Crevice_Thickness");
    for (j = 1; j <= attrs.Count; ++j) {
        var attr = attrs.item(j);
        var partid = bodyPartID;
        var topid = attr.TopoId;
        sm.AddToSelection(partid, topid, false);
    }


    if (sm.SelectedCount) {
      var mehctrls = meshGroup.MeshControls;
      var meshctrl;
      var MeshCtrlObj = null;
      for (var j = 1; j <= mehctrls.Count; j++) {
          meshctrl = mehctrls.item(j);
          if (meshctrl.ControlType != ds.Script.id_Size)
              continue;
          var str = new String(meshctrl.Name);
          if (str.indexOf("Piston-Outer") == -1) continue;
          MeshCtrlObj = meshctrl;
      }

      var Thickness;
      Thickness = getCreviceThickness();

    var Sizing;
    Sizing = Thickness / 3;

    var Meansize = (MaxMeshSize + MinMeshSize) / 2;

    if (Sizing > Meansize)
        Sizing = Meansize;

    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
        if (MeshCtrlObj) {
            MeshCtrlObj.Name = MeshCtrlObj.Name + " (Piston-Outer) ";
            MeshCtrlObj.ESize = Sizing;
            MeshCtrlObj.SizingType = 1; //Hard
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
           
          }
      }
      else {
          var str1 = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
   }
}

function DefinePistonCoreSweepMesh() {

  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var i, j;
  var partId;

  
  var Assys = pm.assemblies;
  if (Assys.Count < 1)
    return;

  var Assy = Assys.Item(1);

  var arrName = new Array();
  var arrBody = new Array();
  var arrPart = new Array();

  var MeshCtrlGrpNode;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      arrPart.push(proto.Part.Id);
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }

  var bodyreq = -1, bodyName, bodyPartID;
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if (str1.indexOf("Piston-Inner") != -1) {
      bodyName = str1;
      bodyreq = arrBody[i];
      bodyPartID = arrPart[i];
      break;
    }
  }
  if(bodyreq<0) return;


  var pos;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  sm.Clear();
  sm.AddToSelection(bodyPartID, bodyreq, false);

  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  var MeshCtrlObj
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("Piston-Inner") == -1) continue;
    MeshCtrlObj = meshctrl;
  }

  if (!MeshCtrlObj) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 5;
      MeshCtrlObj.SourceTargetSelection = 1;
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + bodyName + ")";
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  else {
    var str1 = MeshCtrlObj.Name;
    MeshCtrlObj.GeometrySelection = sm;
    MeshCtrlObj.Name = str1; 
  }

  
  var faceArr = new Array();
  var facePartArr = new Array();

  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if (str1.indexOf("ice-int-chamber-piston") != -1) {
      for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        faceArr.push(topid);
        facePartArr.push(partid);
      }
    }
  }

  
  sm.Clear();
  for (var i = 0; i < faceArr.length; ++i) {
    part = Assy.PartById(facePartArr[i]);
    face = part.BRep.Cell(faceArr[i]);

    if (facePartArr[i] != bodyPartID)
      continue;

    var bodies = face.Bodies;
    if (bodies.Count != 2)
      continue;

    if (bodies.item(1).Id == bodyreq)
      sm.AddToSelection(bodyPartID, face.Id, false);
    if (bodies.item(2).Id == bodyreq)
      sm.AddToSelection(bodyPartID, face.Id, false);
  }

  if ((sm.SelectedCount) && (MeshCtrlObj)) {
    MeshCtrlObj.SourceGeometry = sm;
  }

}


function CreateMeshingOrderSectorComb() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name, str1, str, found, chNs = null;
  var j = 0;
  var partid, topid, pos;

  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var meshGroup = branch.MeshControlGroup;
  var numCases = meshGroup.NumNamedSelectionEntries;
  if (numCases)
    return;

  var arr = new Array();
  var childList = protoGroup.Children;
  var i, j;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);
      ns = ds.Script.addNamedSelection(false, str1, null);
      if (typeof (ns) == "undefined") continue;
      ns.SendToSolver = false;
      ns.WorksheetMeshing = true;
      arr.push(ns);
    }
  }
  if (arr.length) {
    var arrIDs = new Array();
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1.indexOf("Piston-Outer") != -1) {
        arrIDs.push(arr[i].ID);
      }
    }
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1 == "Piston-Inner") {
        arrIDs.push(arr[i].ID);
      }
    }
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1 == "Piston-Inflation") {
        arrIDs.push(arr[i].ID);
      }
    }
    for (i = 0; i < arr.length; ++i) {
        str1 = arr[i].Name;
        if (str1 == "Chamber-Inner-Bottom") {
            arrIDs.push(arr[i].ID);
        }
    }
    for (i = 0; i < arr.length; ++i) {
        str1 = arr[i].Name;
        if (str1 == "Chamber-Outer-Bottom") {
            arrIDs.push(arr[i].ID);
        }
    }
    for (i = 0; i < arr.length; ++i) {
        str1 = arr[i].Name;
        if (str1 == "Chamber-Inner-Top") {
            arrIDs.push(arr[i].ID);
        }
    }
    for (i = 0; i < arr.length; ++i) {
        str1 = arr[i].Name;
        if (str1 == "Chamber-Outer-Top") {
            arrIDs.push(arr[i].ID);
        }
    }


    

    for (i = 0; i < arrIDs.length; ++i) {
      meshGroup.AddNamedSelectionList();
      var numCases = meshGroup.NumNamedSelectionEntries;
      meshGroup.WorkSheetNamedSelectionId(numCases - 1) = arrIDs[i];
      meshGroup.MeshWorksheetNamedSelectionActive(numCases - 1) = 1;
    }
  }
}
//=======================================================================
//Port Flow
//=======================================================================
function IsPortFlow() {
  var retrn = -1; // -1 for unknown, 0 for non-ic case, 1 for ic case.
  var Assys = pm.assemblies;
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_PortFlow");
    if (attrs.Count)
      retrn = 1;
    else
      retrn = 0;
  }
  return retrn;
}
function DefinePortFlowMesh() {
  if (typeof (ds.Script.lv) != "undefined")
    ds.Script.lvFroceOutOfEdit();

  //Set the units to mm
//  ds.Script.doUnitsMenu(2);
  ds.UnitSystemID = 2;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;

  meshGroup.PhysicsPreference = 2;
  meshGroup.SolverPreference = 0;
  meshGroup.AdvancedSizeFunction = 1; //Proximity
  meshGroup.SpanningAngleSF = NormalAngle;
  meshGroup.MaxFaceElementSize = MaxMeshSize;
  meshGroup.MaxSizeSF = MaxMeshSize;
  meshGroup.MinSizeSF = MinMeshSize;
  meshGroup.MeshDefeatureTol = MinMeshSize/2.0;
  meshGroup.ProximityMinSizeSF = ProxMinMeshSize;
  meshGroup.NumCellGapSF = ProxNumCells;
  meshGroup.TransitionSF = GrowthRate;
  meshGroup.PinchTolerance = Pinch;
  meshGroup.NumLayers = NbInflation;
  meshGroup.AutomaticInflation = 0; //0-none, 1-programcontrolled
  //meshGroup.ProximityAccuracy = 1.;
  meshGroup.SmoothingOption = 2;

  meshGroup.CollisionAvoidance = 1;
  meshGroup.InflationMaximumAngle = 180;
  //meshGroup.InflationGapFactor = 1.5;
  meshGroup.ExpansionFactor = 1.1;
  meshGroup.InflationOption = 4; //2-smooth Transition, 4-Last Aspect Ratio
  if (MeshType == 1) {
    meshGroup.FirstLayerHeight=round(RefSize/20.);
  }
  else{
    meshGroup.FirstLayerHeight=round(RefSize/70.);
  }
  meshGroup.LastAspectRatio=3.0;
  meshGroup.MaximumLayers=NbInflation;
  
  
  //cutcell
  if (MeshType == 1) {
    meshGroup.AssemblyMeshingMethod = 1;
    
    meshGroup.ElementOrder = 1;
    meshGroup.NumberOfRetries = 0;
    meshGroup.RelevanceCenter = 1;
    meshGroup.ShapeChecking = 3;
    meshGroup.SpanAngleOption = 2;
    meshGroup.TransitionOption = 1;

    ICDeleteProximitySizing();
    ICDeleteSizeIntChPort();
    ICChamberSizing(0);
    ICPortSizing(0);
    ICOutletFaceSizing();
    ICDelOutletFaceNS();
    //ICNSInflation();
    ICCreateUpdateInflationControl(0);    
  }
  else { //Tet mesh
    if(meshGroup.AssemblyMeshingMethod)
      meshGroup.AssemblyMeshingMethod = 0;

    //meshGroup.FirstLayerHeight = RefSize/5.0;
    //meshGroup.LastAspectRatio = 10;
    //meshGroup.AdvancedInflationOptions = true;

    //Automatic VC
    //ICECreateAutomaticVC(1);
    //ICUpdateNSWithVC();

    ICDefineChSweepMethod();
    ICDefineOutlet();
    ICProximitySizing(0);
    ICChamberSizing(0);
    ICSizeIntChPort();
    ICDeleteBodySizePort();
    ICOutletFaceSizing();
    //ICNSInflation();
    ICCreateUpdateInflationControl(0);
    ICCreateMeshingOrder();
    //ICOutletFaceNS();
    ICEDoAutoPinch();
  }
  RemoveUserNSfromDefaultNS();
  //Change material type to fluid
  ChangMaterialToFluid();
  //Set port flow session variable
  var portflowsessionvarregen = GetPortFlowSessionVariableString();
  ICSetSessionVaribale("ICEngineValveLiftPlaneOff", portflowsessionvarregen);

  if (initialPanelValue == "") {
    CreateSectionPlanes();
    CreateViews();
    DeleteContacts();
  }
}
function ICDeleteProximitySizing() {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    var str = new String(meshctrl.Name);
    if (str.indexOf("(valve-proximity-faces)") != -1) {
      if (ds.Tree.CanDelete(meshctrl.ID))
        ds.Tree.DeleteItem(meshctrl.ID);
      return;
    }
  }
}
function ICProximitySizing(IsRegen) {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  if (meshGroup.AssemblyMeshingMethod)
    return;

  sm.Clear();
  for (var i = 1; i <= nsl.Count; i++) {
    var ns = nsl.item(i);
    str1 = ns.Name;
    if (str1.indexOf("ice-valve-proximity-faces") == -1) continue;
  
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      var pos = str1.indexOf(";");
      var partId = str1.substring(0, pos);
      var topoId = str1.substring(pos + 1);
      sm.AddToSelection(partId, topoId, false);
    }
    break;
  }
  if (sm.SelectedCount) {
    //If it already contains mesh size, return
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj = null;
    for (var j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      var str = new String(meshctrl.Name);
      if (str.indexOf("(valve-proximity-faces)") != -1) {
        MeshCtrlObj = meshctrl;
        break;
      }
    }
    if (!MeshCtrlObj) {
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        MeshCtrlObj.ESize = ProxValveSize;
        MeshCtrlObj.SizingType = 1; //Hard
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (valve-proximity-faces)";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }
    else {
      if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
      if (!IsRegen)
        meshctrl.ESize = ProxValveSize;
    }
  }
}

function ICChamberSizing(IsRegen) {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name, str1, str, found, chNs = null;
  var i, j = 0;
  var partid, topid, pos;

  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var arr = new Array();
  var childList = protoGroup.Children;
  var i, j;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;
    sm.Clear();
    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      var bodies = proto.Part.BRep.Bodies;
      //DE64955: adding all chmaber bodies to BOdySizing definition for cutcell and only chanber body for Hybrid 
      if (MeshType == 1) {
        if (str1.indexOf("Chamber") != -1) 
            sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);
      }
      else {
         if (str1 == "Chamber") 
            sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);
      }
    }
    if(sm.SelectedCount){
      var meshGroup = branch.MeshControlGroup;
      //If it already contains mesh size, return
      var mehctrls = meshGroup.MeshControls;
      var meshctrl;
      var MeshCtrlObj = null;
      for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
          continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("(Chamber)") != -1) {
          MeshCtrlObj = meshctrl;
          break;
        }
      }
      if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
        if (MeshCtrlObj) {
          MeshCtrlObj.ESize = ChSize;
          MeshCtrlObj.SizingTransition = ChGrowthRate;
          MeshCtrlObj.Name = MeshCtrlObj.Name + " (Chamber)";
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
      }
      else {
        if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
          var str1 = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
        }
      
        if (!IsRegen) {
          if (meshGroup.AssemblyMeshingMethod)//cutcell
            meshctrl.SizingTransition = 0;
          else
            meshctrl.SizingTransition = ChGrowthRate;
          meshctrl.ESize = ChSize;
        }
      }
      break;
    }
  }
}

function ICDelOutletFaceNS() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns1, ns2, arr;
  var i = 0; j = 0;
  var nsl;

  nsl = branch.Components;
  for (j=nsl.Count; j >= 1 ; --j) {
    ns1 = nsl.item(j);
    var str = new String(ns1.Name);
    if (str.indexOf("Outplenum-faces") == -1) continue;
    if (ds.Tree.CanDelete(ns1.ID))
      ds.Tree.DeleteItem(ns1.ID);
    break;
  }
}
function ICOutletFaceNS() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name, str1, str, found, chNs = null;
  var i,j = 0;
  var partid, topid, pos;

  var IsSpherical = IsOutletASphere();
  var lContainsSlipwall = false;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  for (i = 1; i <= nsl.Count; i++) {
    var ns = nsl.item(i);
    str1 = ns.Name;
    if (str1.indexOf("ice-slipwall-outplenum") != -1) {
      lContainsSlipwall = true;
      break;
    }
  }
  if (IsSpherical || !lContainsSlipwall)
    return;
  
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var nsl = branch.Components;
  for (j = nsl.Count; j >= 1; --j) {
    ns1 = nsl.item(j);
    var str = new String(ns1.Name);
    if (str.indexOf("Outplenum-faces") != -1)
      return;
  }
  var arr = new Array();
  var childList = protoGroup.Children;
  var i, j;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      if (str1.indexOf("Outplenum") == -1) continue;
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      var body = bodies.item(j);
      var faces = body.Faces;
      for(var k=1;k<=faces.Count;++k)
        sm.AddToSelection(proto.Part.Id, faces.item(k).Id, false);
      str1 = str1 + "-faces";
      ns = ds.Script.addNamedSelection(false, str1, null);
      ns.SendToSolver = false;
      ns.IncludePCInflation = false;
      break;
    }
  }
}
function ICDefineChSweepMethod() {
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  var heightsArr = ICPorFlowGetChHeights();
  if (heightsArr.length == 0)
    return;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("(Chamber") == -1) continue;
    for (var i = 0; i < heightsArr.length; ++i) {
      str = "(Chamber";
      str += i;
      for (var k = 1; k <= mehctrls.Count; k++) {
        meshctrl = mehctrls.item(k);
        if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
          continue;
        var str1 = new String(meshctrl.Name);
        if (str1.indexOf(str) != -1) {
          meshctrl.NDiv = Math.round(heightsArr[i] / RefSize);
          break;
        }
      }
    }
    return;
  }
  
  var arrName = new Array();
  var arrBody = new Array();
  var childList = protoGroup.Children;
  var i, j;
  var partId;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      partId = proto.Part.Id;
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }
  var arrName1 = new Array();
  var arrBody1 = new Array();
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if ((str1 != "Chamber") && str1.indexOf("Chamber") != -1) {
      arrName1.push(arrName[i]);
      arrBody1.push(arrBody[i]);
    }
  }
  var arrName2 = new Array();
  var arrBody2 = new Array();
  for (j = 0; j < arrName1.length; ++j) {
    str = "Chamber";
    str += j;
    for (i = 0; i < arrName1.length; ++i) {
      str1 = arrName1[i];
      if (str1 == str) {
        arrName2.push(str);
        arrBody2.push(arrBody1[i]);
        break;
      }
    }
  }
  //Sweep method for each body
  for (i = 0; i < arrBody2.length; ++i) {
    sm.Clear();
    sm.AddToSelection(partId, arrBody2[i], false);
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 5;
      if (heightsArr.length == arrBody2.length) {
        MeshCtrlObj.SweepESizeType = 1;
        MeshCtrlObj.NDiv = Math.round(heightsArr[i] / RefSize);
      }
      else {
        MeshCtrlObj.SweepESizeType = 0;
        MeshCtrlObj.ESize = RefSize;
      }

      MeshCtrlObj.SweepShape = 2;
      MeshCtrlObj.SweepBiasType = 3;
      MeshCtrlObj.SweepBiasValue = 1.0;
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + arrName2[i] + ")";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
}
function ICDefineOutlet() {
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("(Outplenum)") != -1)
      return;
  }
  var arrName = new Array();
  var arrBody = new Array();
  var childList = protoGroup.Children;
  var i, j;
  var partId;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      partId = proto.Part.Id;
      arrName.push(str1);
      arrBody.push(bodies.item(j).Id);
    }
  }
  //============================
  //Outlet plenum
  //============================
  var outlet=0,plenumName;
  for (i = 0; i < arrName.length; ++i) {
    str1 = arrName[i];
    if (str1.indexOf("Outplenum") != -1) {
      plenumName = str1;
      outlet = arrBody[i];
      break;
    }
  }
  var lContainsSlipwall = false;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  for (i = 1; i <= nsl.Count; i++) {
    var ns = nsl.item(i);
    str1 = ns.Name;
    if (str1.indexOf("ice-slipwall-outplenum") != -1) {
      lContainsSlipwall = true;
      break;
    }
  }  
  var IsSpherical = IsOutletASphere();
  if (outlet && !IsSpherical && lContainsSlipwall) {
    sm.Clear();
    sm.AddToSelection(partId, outlet, false);
    var MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_BodyMeshType);
    if (MeshCtrlObj) {
      MeshCtrlObj.Value = 7; //Multizone method
      sm.Clear();
      for (i = 1; i <= nsl.Count; i++) {
        var ns = nsl.item(i);
        str1 = ns.Name;
        if (str1.indexOf("ice-slipwall-outplenum") != -1 || ((str1.indexOf("int-Chamber") != -1) && (str1.indexOf("-Outplenum") != -1))) {
          for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
            str1 = String(ns.GetUnsuppressedPartTopoPair(k));
            var pos = str1.indexOf(";");
            var partId = str1.substring(0, pos);
            var topoId = str1.substring(pos + 1);
            sm.AddToSelection(partId, topoId, false);
          }
        }
      }
      if (sm.SelectedCount) {
        ICAddOutletBottomFace();
        MeshCtrlObj.SourceTargetSelection = 1;
        MeshCtrlObj.SourceGeometry = sm;
      }
      MeshCtrlObj.SubMultizoneMapped = 1;
      MeshCtrlObj.MZSurfaceMeshMethod = 1; //DE34841, program controlled method is giving high cell count.
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + plenumName + ")";
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
}

function ICOutletFaceSizing() {
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    var str = new String(meshctrl.Name);
    if (str.indexOf("(Outplenum-cyl)") != -1) {
      meshctrl.ESize = 1.5 * RefSize;
      return;
    }
  }

  var i, j, outletBody = null, partId = null;
  var childList = protoGroup.Children;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      if (str1.indexOf("Outplenum") != -1) {
        partId = proto.Part.Id;
        outletBody = bodies.item(j);
        break;
      }
    }
  }
  if (outletBody) {
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;
    sm.Clear();
    if (IsOutplenumACylinder()) {
      sm.AddToSelection(partId, outletBody.Id, false);
    }
    else {
      for (i = 1; i <= nsl.Count; i++) {
        var ns = nsl.item(i);
        str1 = ns.Name;
        if (str1.indexOf("ice-cyl") == -1) continue;
        var Assys = pm.assemblies;
        if (!Assys.Count) return;
        var Assy = Assys.Item(1);

        for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
          str1 = String(ns.GetUnsuppressedPartTopoPair(k));
          var pos = str1.indexOf(";");
          var partId = str1.substring(0, pos);
          var topoId = str1.substring(pos + 1);
          var part = Assy.PartById(partId);
          var face = part.BRep.Cell(topoId);
          var bodies = face.Bodies;
          if (!bodies.Count) continue;
          var body = bodies.item(1);
          if (body.Id == outletBody.Id)
            sm.AddToSelection(partId, topoId, false);
        }
        break;
      }
    }
    if (sm.SelectedCount) {
      var MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        MeshCtrlObj.ESize = 1.5 * RefSize;
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (Outplenum-cyl)";
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }
  }
}
function ICNSInflation() {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  for (var i = 1; i <= nsl.Count; ++i) {
    var ns = nsl.item(i);
    var str1 = new String(ns.Name);
    if ((str1.indexOf("ice-cyl") != -1) || (str1.indexOf("ice-user-") != -1))
      ns.IncludePCInflation = true;
    else if (str1.indexOf("ice-slipwall") != -1)
      ns.IncludePCInflation = true;
    else if (str1.indexOf("ice-valve-proximity-faces") != -1) {
      ns.IncludePCInflation = true;
      ns.SendToSolver = false;
    }
  }
}
function ICGetNumExportNS() {
  var Assys = pm.assemblies;
  var NumNS = 0;
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_Num_Export_NS");
    if (attrs.Count) {
      var attr = attrs.item(1);
      NumNS = attr.Integer;
    }
  }
  return NumNS;
}
function ICGetKeyGrid() {
  var Assys = pm.assemblies;
  var KeyGrid = 0;
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_Kegrid");
    if (attrs.Count) {
      var attr = attrs.item(1);
      var str = new String(attr.Integer);
      KeyGrid = str
    }
  }
  return KeyGrid;
}
function ICGetValveOpeningTolerence() {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_LiftAngle_Tol");
  var Tolerence = 0.;
  for (var i = 1; i <= attrs.Count; ++i) {
    var attr = attrs.item(i);
    if (attr.Type != 3) //string
      continue;
    var str = new String(attr.String);
    var str1 = ";";
    var pos = str.indexOf(str1);
    if (pos > 0)
      str = str.substring(0, pos);
    else
      str = str.substring(0);
    Tolerence = new Number(str);
  }
  return Tolerence;
}
function IsPistonType1(){
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_LiftAngle_Tol");
  var lreturn = 0;
  for (var i = 1; i <= attrs.Count; ++i) {
    var attr = attrs.item(i);
    if (attr.Type != 3) //string
      continue;
    var str = new String(attr.String);
    var str1 = "ChDecompose-";
    var pos = str.indexOf(str1);
    if (pos > 0) {
      str = str.substring(pos + str1.length);
      pos = str.indexOf(";");
      if (pos > 0)
        str = str.substring(0, pos);
      else
        str = str.substring(0);
      if (str == "Y")
        lreturn = 1;
    }
  }
  return lreturn;
}
function ICPorFlowGetChHeights() {
  var heights = new Array();
  var Assys = pm.assemblies;
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_PlanesOffset");
    if (attrs.Count) {
      var attr = attrs.item(1);
      var str = new String(attr.String);
      var dist = str.split(";");
      for (var i = 1; i < dist.length; ++i) {
        heights.push(dist[i] - dist[i - 1]);
      }
    }
  }
  return heights;
}
function ICCreateMeshingOrder() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name,str1, str, found, chNs = null;
  var j = 0;
  var partid, topid, pos;
  
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var meshGroup = branch.MeshControlGroup;
  var numCases = meshGroup.NumNamedSelectionEntries;
  if (numCases)
    return;
      
  var arr = new Array();
  var childList = protoGroup.Children;
  var i, j;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);
      ns = ds.Script.addNamedSelection(false, str1, null);
      if (typeof (ns) == "undefined") continue;
      ns.SendToSolver = false;
      ns.WorksheetMeshing = true;
      if(str1.indexOf("Outplenum") != -1)
        ns.IncludePCInflation = false;
      else
        ns.IncludePCInflation = true;

      arr.push(ns);
    }
  }
  if (arr.length) {
    var arrIDs = new Array();
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1.indexOf("Inplenum") != -1) {
        arrIDs.push(arr[i].ID);
      }
    }
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1.indexOf("-Port") != -1) {
        arrIDs.push(arr[i].ID);
      }
    }
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1 == "Chamber") {
        arrIDs.push(arr[i].ID);
      }
    }
    var arrCh = new Array();
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if ((str1 != "Chamber") && (str1.indexOf("Chamber") != -1)) {
        arrCh.push(arr[i]);
      }
    }
    for (j = 0; j < arrCh.length; ++j) {
      str = "Chamber";
      str += j;
      for (i = 0; i < arrCh.length; ++i) {
        str1 = arrCh[i].Name;
        if (str1== str) {
          arrIDs.push(arrCh[i].ID);
          break;
        }
      }
    }
    for (i = 0; i < arr.length; ++i) {
      str1 = arr[i].Name;
      if (str1.indexOf("Outplenum") != -1) {
        arrIDs.push(arr[i].ID);
      }
    }

    for (i = 0; i < arrIDs.length; ++i) {
      meshGroup.AddNamedSelectionList();
      var numCases = meshGroup.NumNamedSelectionEntries;
      meshGroup.WorkSheetNamedSelectionId(numCases - 1) = arrIDs[i];
      meshGroup.MeshWorksheetNamedSelectionActive(numCases - 1) = 1;
    }
  }
}
function ICResetNSForBodies() {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name, str1, str, found, chNs = null;
  var j = 0;
  var partid, topid, pos;

  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var childList = protoGroup.Children;
  var i, j,k;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      sm.Clear();
      var bodies = proto.Part.BRep.Bodies;
      sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);

      for (k = 1; k <= nsl.Count; ++k) {
        ns = nsl.item(k);
        if (!ns.WorksheetMeshing) continue;
        str = String(ns.Name);
        if (str != str1) continue;
        if(ns.NumInSelection != sm.SelectedCount)
          ns.GeometrySelection = sm;
        break;
      }
    }
  }
}

function GeneratePortFlowMesh() {
  ICDoModelPreviewMesh();
 
  //If inflation fails, then ask for generate mesh without inflation, which will be instantaneous
  if (CheckForTheErrorMessage("Assembly meshing Inflation meshing failed.")) {
    var message = "Assembly meshing Inflation meshing failed. \nWould you like to generate mesh without inflation (i.e suppress the inflation mesh controls) ?";
    var yesPressed = DisplayYesNoDialog(message);
    if (yesPressed) {
      var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
      if (!meshGroup) return;
      var mehctrls = meshGroup.MeshControls;
      var meshctrl = null;
      var inflationFound = false;
      for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Inflation)
          continue;
        if (meshctrl.SubValue)
          meshctrl.SubValue = false;
        inflationFound = true;
      }
      if(inflationFound)
        ICDoModelPreviewMesh();
    }
  }
}
function ChangMaterialToFluid() {
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup) return;
  var childList = protoGroup.Children;
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;
    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;
    for (var j = 1; j <= protoList.Count; j++) {
      proto = protoList.item(j);
      if (proto.Phase != 1)
        proto.Phase = 1;
    }
  }
}
function GetPortFlowSessionVariableString() {
  var Assys = pm.assemblies;
  var strplaneoff = "";
  var strvalvelift = "";
  
  //For Valve lift
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_ValveLifts");
    if (attrs.Count) {
      var attr = attrs.item(1);
      strvalvelift = new String(attr.String);
    }
  }
  //For plane offset
  if (Assys.Count) {
    var Assy = Assys.Item(1);
    var attrs = Assy.AttributesByName(1,"ICEngine_PlanesOffset");
    if (attrs.Count) {
      var attr = attrs.item(1);
      strplaneoff = new String(attr.String);
    }
  }
  var str = strvalvelift + strplaneoff;
  return str;
}
function ICECreateVCPortBottom() {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var i,j,k;

  var arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-port") != -1)) {
      arr.push(ns);
    }
  }

  //Sweep for bottom ports.
  var pos, partid, partIdInt, part;
  var attrs, attr;
  var face/*IABrFace*/, edges, edge, body, bodies, faces;
  var facesArr, partArr, bodiesArr;
  partArr = new Array();
  bodiesArr = new Array();

  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      break;
    }
    partIdInt = parseInt(partid);
    part = Assy.PartById(partIdInt);
    attrs = part.AttributesByName(1,"ICEngine_SweepSources");
    for (i = 1; i <= attrs.Count; ++i) {
      attr = attrs.item(i);
      face = part.BRep.Cell(attr.TopoId);
      bodies = face.Bodies;
      if (bodies.Count == 2) {
        partArr.push(partIdInt);
        bodiesArr.push(bodies.item(1));
        bodiesArr.push(bodies.item(2));
      }
    }
  }
  for (j = 0; j < partArr.length; ++j) {
    var faceArr = new Array();
    var faceArr1 = new Array();
    body = bodiesArr[2 * j]
    faces = body.Faces;
    for (k = 1; k <= faces.Count; k++) {
      face = faces.item(k);
      bodies = face.Bodies;
      if (bodies.Count > 1) continue;
      faceArr.push(face.Id);
    }
    body = bodiesArr[2 * j+1]
    faces = body.Faces;
    for (k = 1; k <= faces.Count; k++) {
      face = faces.item(k);
      bodies = face.Bodies;
      if (bodies.Count > 1) continue;
      faceArr.push(face.Id);
    }
    part = Assy.PartById(partArr[j]);
    for (k = 0; k < faceArr.length; ++k) {
      for (i = 0; i < faceArr1.length; ++i) {
        if (faceArr1[i] == faceArr[k])
          break;
      }
      if (i < faceArr1.length) continue;
      sm.Clear();
      sm.AddToSelection(partArr[j], faceArr[k], false);
      sm.floodSelect(0.5);//select by 0.5 deg
      var vcArr1 = new Array();      
      var vcArr2 = new Array();      
      var vcArr3 = new Array();      
      if(sm.SelectedCount==1)
        continue;
      var thirdBodyId=0;
      for (i = 1; i <= sm.SelectedCount; i++) {
        topoId = sm.SelectedEntityTopoID(i);
        face = part.BRep.Cell(topoId);
        bodies = face.Bodies;
        var bodyId = bodies.item(1).Id;
        if (bodiesArr[2 * j].Id == bodyId){
          vcArr1.push(topoId);
          if(i > 1)
            faceArr1.push(topoId);
        }
        else if (bodiesArr[2 * j + 1].Id == bodyId){
          vcArr2.push(topoId);
          if(i > 1)
            faceArr1.push(topoId);
        }
        else if(false){//Lets not merge port faces, as it takes lot of time.
          if(thirdBodyId == 0)
            thirdBodyId = bodyId;
          if(thirdBodyId == bodyId)
            vcArr3.push(topoId);
        }
      }
      if(vcArr1.length > 1){
        sm.Clear();
        for(i=0; i<vcArr1.length;++i)
          sm.AddToSelection(partArr[j], vcArr1[i], false);
        ICEAddVirtualFace();
      }
      if (vcArr2.length > 1) {
        sm.Clear();
        for (i = 0; i < vcArr2.length; ++i)
          sm.AddToSelection(partArr[j], vcArr2[i], false);
        ICEAddVirtualFace();      
      }
      if (vcArr3.length > 1) {
        sm.Clear();
        for (i = 0; i < vcArr3.length; ++i)
          sm.AddToSelection(partArr[j], vcArr3[i], false);
        ICEAddVirtualFace();
      }
    }
  }
}
function IsOutletASphere() {
  var lReturn = false;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  sm.Clear();
  var nsOutlet = null;
  for (var i = 1; i <= nsl.Count; i++) {
    var ns = nsl.item(i);
    var str1 = ns.Name;
    if (str1.indexOf("ice-outlet") != -1) {
      nsOutlet = ns;
      break;
    }
  }
  if (nsOutlet) {
    var Assys = pm.assemblies;
    if (!Assys.Count) return;
    var Assy = Assys.Item(1);
    var ns = nsOutlet;
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      var pos = str1.indexOf(";");
      var partId = str1.substring(0, pos);
      var topoId = str1.substring(pos + 1);
      var part = Assy.PartById(partId);
      var face = part.BRep.Cell(topoId);
      if (face.SurfaceType == ds.Script.si_kABrSurfaceSphere) {
        lReturn = true;
        break;
      }
    }
  }
  return lReturn;
}
function IsOutplenumACylinder() {
  var lReturn = false;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  sm.Clear();
  var nsOutlet = null, nsCyl=null;
  for (var i = 1; i <= nsl.Count; i++) {
    var ns = nsl.item(i);
    var str1 = ns.Name;
    if (str1.indexOf("ice-outlet") != -1) {
      nsOutlet = ns;
    }
    if (str1.indexOf("ice-cyl") != -1) {
      nsCyl = ns;
    }
  }
  if (nsOutlet && nsCyl) {
    var Assys = pm.assemblies;
    if (!Assys.Count) return;
    var Assy = Assys.Item(1);
    var body = null;
    var faceArr = new Array();
    var ns = nsOutlet;
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      var pos = str1.indexOf(";");
      var partId = str1.substring(0, pos);
      var topoId = str1.substring(pos + 1);
      faceArr.push(topoId);
      if (!body) {
        var part = Assy.PartById(partId);
        var face = part.BRep.Cell(topoId);
        var bodies = face.bodies;
        body = bodies.item(1);
      }
    }
    ns = nsCyl;
    for (var k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(k));
      var pos = str1.indexOf(";");
      var partId = str1.substring(0, pos);
      var topoId = str1.substring(pos + 1);
      faceArr.push(topoId);
    }
    if (body) {
      lReturn = true;
      var faces = body.Faces;
      for (var k = 1; k <= faces.Count; k++) {
        var face = faces.item(k);
        var bodies = face.bodies;
        if (bodies.Count > 1) continue;
        var found = false;
        for (var i = 0; (!found) && (i < faceArr.length); i++) {
          if (face.Id == faceArr[i])
            found = true;
        }
        if (!found) {
          lReturn = false;
          break;
        }
      }
    }
  }
  return lReturn;
}
function ICAddOutletBottomFace() {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var ns1=null,ns2=null;
  for (var i = 1; i <= nsl.Count; i++) {
    var ns = nsl.item(i);
    str1 = ns.Name;
    if (str1.indexOf("ice-slipwall-outplenum") != -1)
      ns1= ns;
    else if (str1.indexOf("ice-outlet") != -1){
      ns2=ns;
    }
  }
  if(!ns1 || !ns2)
    return;
  var Assys = pm.assemblies;
  if (!Assys.Count) return;
  var Assy = Assys.Item(1);

  var edgeArr = new Array();
  for (var k = 0; k < ns1.NumInSelection - ns1.NumSuppressedItems; k++) {
    var str1 = String(ns1.GetUnsuppressedPartTopoPair(k));
    var pos = str1.indexOf(";");
    var partId = str1.substring(0, pos);
    var topoId = str1.substring(pos + 1);
    var part = Assy.PartById(partId);
    var face = part.BRep.Cell(topoId);
    var edges = face.Edges;
    for (var i = 1; i <= edges.Count; ++i) {
      var edge = edges.item(i);
      edgeArr.push(edge.Id);
    }
  }
  if(edgeArr.length == 0) return;
  for (var k = 0; k < ns2.NumInSelection - ns2.NumSuppressedItems; k++) {
    var str1 = String(ns2.GetUnsuppressedPartTopoPair(k));
    var pos = str1.indexOf(";");
    var partId = str1.substring(0, pos);
    var topoId = str1.substring(pos + 1);
    var part = Assy.PartById(partId);
    var face = part.BRep.Cell(topoId);
    var edges = face.Edges;
    var i=1;
    for(i=1; i<=edges.Count; ++i){
      var j = 0;
      var edge = edges.item(i);
      for(j=0;j<edgeArr.length; ++j){
        if (edge.Id == edgeArr[j])
          break;
      }
      if (j < edgeArr.length) 
        break;
    }
    if (i > edges.Count) {
      sm.AddToSelection(partId, face.Id, false);
      break;
    }
  }
}
function ICProjectToUnderlyingGeomVC() {
  var branch, VCellGroup;
  var i;
  var vCells, vCell;

  //Automatic virtual cell creation
  branch = ds.Tree.FirstActiveBranch;
  VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup) return;

  vCells = VCellGroup.VirtualCells;
  if (!vCells.Count) return;
  for (i = 1; i <= vCells.Count; i++) {
    vCell = vCells.item(i);
    if(!vCell.ProjectToGeometry)
      vCell.ProjectToGeometry = 1;
  }
}
function ICIsInflationRequiredOnOutlet() {
  var lReturn = true;
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;

  if (meshGroup.AssemblyMeshingMethod == 0) {
    lReturn = false;
    var IsSpherical = IsOutletASphere();
    var lContainsSlipwall = false;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    for (var i = 1; i <= nsl.Count; i++) {
      var ns = nsl.item(i);
      var str1 = ns.Name;
      if (str1.indexOf("ice-slipwall-outplenum") != -1) {
        lContainsSlipwall = true;
        break;
      }
    }
    if(IsOutplenumACylinder())
      lReturn = false;
    else if (IsSpherical || !lContainsSlipwall)
      lReturn = true ;
  }
  return lReturn;
}
function ICCreateUpdateInflationControl(regen) {
  var branch = ds.Tree.FirstActiveBranch;
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  var meshGroup = branch.MeshControlGroup;
      
  var bodyArr = new Array();
  var partArr = new Array();
  var childList = protoGroup.Children;
  var i, j;
  sm.Clear();
  var lOutlet = ICIsInflationRequiredOnOutlet();
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      if(!lOutlet){
        if (str1.indexOf("Outplenum") != -1)
          continue;
      }
      if (meshGroup.AssemblyMeshingMethod == 0) {
       if((str1 != "Chamber") && (str1.indexOf("Chamber") != -1))
        continue;
      }
      var bodies = proto.Part.BRep.Bodies;
      partArr.push(proto.Part.Id);
      bodyArr.push(bodies.item(j));
      sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);
    }
  }

  //If it already contains mesh size, return
  var MeshCtrlObj=null;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_Inflation)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("(all-faces)") != -1) {
      MeshCtrlObj=meshctrl;
      break;
    }
  }
  //Inflation
  if(!MeshCtrlObj){
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Inflation);
    if (MeshCtrlObj) {
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (all-faces)"
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
  }
  if(!regen)
    MeshCtrlObj.MaximumLayers = NbInflation;
  if (MeshCtrlObj.GeometryNum != sm.SelectedCount) 
    MeshCtrlObj.GeometrySelection = sm;
  sm.Clear();
  var faceArr = new Array();
  var facePartArr = new Array();  
  var nsl = ds.Tree.FirstActiveBranch.Components;
  var pos,partid,topid,str1;
  if (!nsl) return;
  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if ((str1.indexOf("ice-sym") != -1) || (str1.indexOf("ice-inlet") != -1) || (str1.indexOf("ice-outlet") != -1)) {
      for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        topid = str1.substring(pos + 1);
        faceArr.push(topid);
        facePartArr.push(partid);
      }
    }
  }
  for (var i = 0; i < bodyArr.length; ++i) {
    var body = bodyArr[i];
    var face, faces, bodies;
    faces = body.Faces;
    for (var j = 1; j <= faces.Count; ++j) {
      face = faces.item(j);
      bodies = face.Bodies;
      if (bodies.Count > 1)
        continue;
      var k = 0;
      for (k = 0; k < faceArr.length; ++k) {
        if(facePartArr[k] != partArr[i]) 
          continue;
        if (face.Id == faceArr[k])
          break;
      }
      if (k == faceArr.length)
        sm.AddToSelection(partArr[i], face.Id, false);
    }
  }
  if (sm.SelectedCount)
    MeshCtrlObj.SourceGeometry = sm;
}
function CreateSectionPlanes() {
  var branch = ds.Tree.FirstActiveBranch;
  var coordSys = branch.CoordinateSystems;
  if (!ds.Graphics || !coordSys)
    return;
  if (typeof (ds.Script.lv) == "undefined")
  return;
  
  if(ds.Script.sectionPaneListView.ListItems.Count > 0)
    return;
  for (var i = 1; i <= coordSys.count; ++i) {
    var coord = coordSys.item(i);
    if (!coord) continue;
    var name = coord.Name;
    if (name.indexOf("ice_cutplane") != -1) {
      ds.Graphics.CreateSlicePlane(coord.ID);
    }
  }
  if (ds.Script.sectionPaneListView) {
    for (var i = 1; i <= ds.Script.sectionPaneListView.ListItems.Count; i++) {
      var item = ds.Script.sectionPaneListView.ListItems.Item(i);
  	  item.Checked = false;
  	}
  	ds.Script.showSectionPlanesPane(true);
  }
}
function CreateViews() {
  var branch = ds.Tree.FirstActiveBranch;
  var coordSys = branch.CoordinateSystems;
  if (!ds.Graphics || !coordSys)
    return;
  if (typeof (ds.Script.lv) == "undefined")
    return;
  if ((ds.Script.modelViewsPaneList)&&(ds.Script.modelViewsPaneList.ListItems.Count > 0))
    return;

  var path = GetFilePath();
  if (path == "")
    return;
  if (typeof (ds.Script.lv) == "undefined")
    return;
  ds.Graphics.View = ds.Script.eIso;
  ds.Graphics.Redraw(1);
  var modelViews = ds.Graphics.ModelViews;
  path = path + "/ICEngineView.xml"
  modelViews.AddCurModelView();
  modelViews.ExportModelViews(path);
  var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject"); 

  if (!fileSys.FileExists(path)) 
    return;
  var ForReading = 1;
  var f = fileSys.GetFile(path);
  var TristateUseDefault = -2; //Opens the file using the system default
  var ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
  var viewStr = ts.ReadLine();
  ts.Close();
  var pos = viewStr.indexOf("<ModelView ");
  if(pos <= 0) return;
  var iceViewStr = viewStr.substr(0,pos);
  viewStr = getStringBetweenLimits(viewStr, "<ModelView ", "</ModelView>");
  var focX = getStringBetweenLimits(viewStr, "<FocX>", "</FocX>");
  var focY = getStringBetweenLimits(viewStr, "<FocY>", "</FocY>");
  var focZ = getStringBetweenLimits(viewStr, "<FocZ>", "</FocZ>");
  var locX = getStringBetweenLimits(viewStr, "<LocX>", "</LocX>");
  var locY = getStringBetweenLimits(viewStr, "<LocY>", "</LocY>");
  var locZ = getStringBetweenLimits(viewStr, "<LocZ>", "</LocZ>");
  var rorCentX = getStringBetweenLimits(viewStr, "<RotCenterX>", "</RotCenterX>");
  var rorCentY = getStringBetweenLimits(viewStr, "<RotCenterY>", "</RotCenterY>");
  var rorCentZ = getStringBetweenLimits(viewStr, "<RotCenterZ>", "</RotCenterZ>");
  var rorCentNum = getStringBetweenLimits(viewStr, "<RotCenterNum>", "</RotCenterNum>");
  pos = viewStr.indexOf("<ZoomF>");
  var viewStr1 = viewStr.substr(pos);
  var dist = Math.sqrt((locX - focX) * (locX - focX) + (locY - focY) * (locY - focY) + (locZ - focZ) * (locZ - focZ));
  var viewIndex = 1;
  var axis = getCylAxis();
  var viewUpVStr = "<UpVX>0</UpVX><UpVY>0</UpVY><UpVZ>1</UpVZ>";
  if (axis.length > 2) {
    axis[0] = -1 * new Number(axis[0]);
    axis[1] = -1 * new Number(axis[1]);
    axis[2] = -1 * new Number(axis[2]);
    viewUpVStr = "<UpVX>" + axis[0].toString(10) + "</UpVX><UpVY>" + axis[1].toString(10) + "</UpVY><UpVZ>" + axis[2].toString(10) + "</UpVZ>";
  }
  for (var i = 1; i <= coordSys.count; ++i) {
    var coord = coordSys.item(i);
    if (!coord) continue;
    var name = coord.Name;
    if (name.indexOf("ice_cutplane") != -1) {
      locX = new Number(focX) - dist * coord.ZDirectionXValue;
      locY = new Number(focY) - dist * coord.ZDirectionYValue;
      locZ = new Number(focZ) - dist * coord.ZDirectionZValue;
      iceViewStr = iceViewStr + "<ModelView Name=\"View " + viewIndex.toString(10) + "\"><RotCenterX>" + rorCentX.toString(10) + "</RotCenterX><RotCenterY>" + rorCentY.toString(10) + "</RotCenterY><RotCenterZ>" + rorCentZ.toString(10) + "</RotCenterZ><RotCenterNum>" + rorCentNum.toString(10) + "</RotCenterNum><LocX>" + locX.toString(10) + "</LocX><LocY>" + locY.toString(10) + "</LocY><LocZ>" + locZ.toString(10) + "</LocZ>" + viewUpVStr + viewStr1 +"</ModelView>";
      viewIndex++;
    }
  }
  iceViewStr = iceViewStr + "</ModelViewsManager>";
  var textStream = fileSys.CreateTextFile(path, true);
  textStream.WriteLine(iceViewStr);
  textStream.Close();
  modelViews.ImportModelViews(path);
  ds.Script.showModelViewsPane(true);
  if (!ds.Script.modelViewsPaneList)
    return;
  var listSize = ds.Graphics.ModelViews.RefreshModelViews();
  ds.Script.modelViewsPaneList.ListItems.Clear();
  for (var i = 0; i < listSize; i++) {
    var str = ds.Graphics.ModelViews.GetModelViewName(i + 1);
    ds.Script.modelViewsPaneList.ListItems.Add(null, null, str);
  }
  for (var i = 1; i < viewIndex; i++) {
    ds.Graphics.ModelViews.ApplyModelView(i);
    ds.Graphics.Redraw(i);
    ds.Script.doGraphicsFit();
    ds.Graphics.ModelViews.UpdateViewToEntry(i);
  }
}
function getCylAxis(){
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_Cyl_Axis");
  var CA = 0.;
  var axis = new Array();
  for (var i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.String);
    if(str != "")
      axis = str.split(";");
  }
  return axis;
}
function getStringBetweenLimits(inputStr,limit1,limit2){
  var   ret="";
  var pos1 = inputStr.indexOf(limit1);
  var pos2 = inputStr.indexOf(limit2);
  if((pos1 >=0) && (pos2 >= limit1.length) ){
    ret = inputStr.substr(pos1+limit1.length,pos2-pos1-limit1.length);
  }
  return ret;
}
function GetFilePath() {
  //Write file
  var path = ds.ActiveFile;
  if (path != "") {
    path = path.substring(0, path.length - 5);
    path = path + "xml";
    var pos = -1;
    if (ds.Script.platform == "UNIX")
      pos = path.lastIndexOf("/");
    else
      pos = path.lastIndexOf("\\");
    if (pos > 0)
      path = path.substring(0,pos);
  }
  else {
    path = ds.Tree.FirstActiveBranch.PrototypeGroup.CADFile;
    var pos = -1;
    if (ds.Script.platform == "UNIX")
      pos = path.indexOf("ICE/DM");
    else
      pos = path.indexOf("ICE\\DM");
    if (pos > 0) {
      path = path.substring(0, pos);
      path = path + "global/MECH";
    }
    else {
      path = "";
    }
  }
  return path;
}

//Port flow regeneration
function ResetProximityFaceSizing() {
  var i, j, k, l, str;
  var nsl, ns;
  var found;
  var Assys, Assy;
  var ns, name, found, intPistonNs = 0;
  var partid, topid, pos;
  
  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;

  var meshSize = getPanelRefSize();
  var valveLifts = getValveLifts();
  var minLift = 0.;
  for (var i = 0; i < (valveLifts.length) / 2; ++i) {
    if (i == 0)
      minLift = valveLifts[2 * i + 1];
    else if (minLift > valveLifts[2 * i + 1])
      minLift = valveLifts[2 * i + 1];
  }

  minLift = minLift / 8;
  if (minLift < meshSize / 8.0)
    minLift = meshSize / 8.0;
  else if (minLift > meshSize)
    minLift = meshSize;


  //Finding control
  var mehctrls = meshGroup.MeshControls;
  var meshctrlSize = null;
  for (i = 1; i <= mehctrls.Count; i++) {
    meshctrl = mehctrls.item(i);
    var str1 = new String(meshctrl.Name);
    if ((str1.indexOf("valve-proximity-faces") != -1)) {
      if (meshctrl.ControlType == ds.Script.id_Size)
        meshctrlSize = meshctrl;
    }
  }
  if (meshctrlSize) {
    meshctrlSize.ESize = minLift;
  }
}
function ResetChSweepPortFlow() {
  var i, j, k, l, str;
  var nsl, ns;
  var found;
  var Assys, Assy;
  var ns, name, found, intPistonNs = 0;
  var partid, topid, pos;
  
  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;

  var heightsArr = ICPorFlowGetChHeights();
  if (heightsArr.length == 0)
    return;

  var mehctrls = meshGroup.MeshControls;
  var meshctrlSwp = null;
  var meshSize = getPanelRefSize();
  for (j = 0; j < heightsArr.length; ++j) {
    str = "(Chamber";
    str += j;
    //finding chamber controls
    meshctrlSwp = null;
    for (i = 1; i <= mehctrls.Count; i++) {
      meshctrl = mehctrls.item(i);
      var str1 = new String(meshctrl.Name);
      if ((str1.indexOf(str) != -1)) {
        if (meshctrl.ControlType == ds.Script.id_BodyMeshType)
          meshctrlSwp = meshctrl;
      }
    }
    if (meshctrlSwp) {
      meshctrlSwp.NDiv = Math.round(heightsArr[j] / meshSize);
    }

  }

}

function DeleteContacts() {
  var branch = ds.Tree.FirstActiveBranch;
  var contactGroup;
  if(branch)
    contactGroup = branch.ContactGroup;
  if (contactGroup) {
    contactGroup.DetectionMode = 0;

    var connections = branch.ConnectionGroups;
    if (connections) {
      for (var j = 1; j <= connections.Count; ++j) {
        var connection = connections.item(j);
        if (ds.Tree.CanDelete(connection.ID))
          ds.Tree.DeleteItem(connection.ID);
      }
    }
  }
  /*ds.Script.changeActiveObject(branch.ContactGroup.Id);
  ds.Script.doAutoConnectionsGeneration();*/
}
function ICDeleteSizeIntChPort() {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    var str = new String(meshctrl.Name);
    if (str.indexOf("(int-ch-port)") != -1) {
      if (ds.Tree.CanDelete(meshctrl.ID))
        ds.Tree.DeleteItem(meshctrl.ID);
      return;
    }
  }
}
function ICSizeIntChPort() {
  var branch = ds.Tree.FirstActiveBranch;

  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var meshGroup = branch.MeshControlGroup;
  //If it already contains mesh size, return
  var MeshCtrlObj=null;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_Size)
      continue;
    var str = new String(meshctrl.Name);
    if (str.indexOf("(int-ch-port)") != -1) {
      MeshCtrlObj=meshctrl;
      meshctrl.ESize = ChSize;
      break;
    }
  }

  if (!MeshCtrlObj) {
    var childList = protoGroup.Children;
    var i, j;
    var protoList=null;
    for (i = 1; i <= childList.Count; i++) {
      var child = childList.Item(i);
      if (ds.Script.id_BodyGroup != child.Class) continue;

      protoList = child.Prototypes;
      if (protoList && protoList.count)
        break;
    }
    if(!protoList) return;
    var partId;
    var chBody=null, portBodies = new Array();
    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      partId = proto.Part.Id;
      str1 = String(proto.Name);
      var bodies = proto.Part.BRep.Bodies;
      if (str1 == "Chamber")
        chBody = bodies.item(j);
      else if (str1.indexOf("-Port") > -1) {
        portBodies.push(bodies.item(j).Id);
      }
    }
    if (!chBody) return;

    var face, faces, bodies;
    faces = chBody.Faces;
    sm.Clear();
    for (j = 1; j <= faces.Count; ++j) {
      face = faces.item(j);
      bodies = face.Bodies;
      if (bodies.Count != 2) continue;
      var bodyId = bodies.item(1).Id;
      if (chBody.Id == bodyId)
        bodyId = bodies.item(2).Id;
      for (i = 0; i < portBodies.length; ++i) {
        if (bodyId == portBodies[i]) break;
      }
      if(i < portBodies.length)
        sm.AddToSelection(partId, face.Id, false);
    }
    if (sm.SelectedCount) {
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
      if (MeshCtrlObj) {
        MeshCtrlObj.ESize = ChSize;
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (int-ch-port)";
        var MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }
  }
}
function DisplayYesNoDialog(message) {
  var htmdlg = g_oApplet.Script.AnsObjectFactory.CreateDispatchObject(
	"WBControls.WBHTMLDialog.182");
  var xfer = g_oApplet.Script.AnsObjectFactory.CreateDispatchObject(
	"WBControls.DlgArgs.182");

  var dialog_title = "IC Generate Mesh";
  var htmurl = installDir + "/html/ICYesNoPrompt.htm";
  xfer("dialog") = htmdlg;
  xfer("message") = message;
  htmdlg.AllowResize = true;
  htmdlg.DoDialog(g_oApplet.Script.wb.hWnd, htmurl, xfer, false, 360, 110, 0, dialog_title);
  return xfer("YesButton");
}
function CheckForTheErrorMessage(message) {
  var MessageDatabase = ds.Tree.MessageDatabase;
  var nb = MessageDatabase.NumMessages;
  var messageFound = false;
  for (var i = 0; i < nb; ++i) {
    var msgObj = MessageDatabase.GetMessage(i);
    if (msgObj == null)
      continue;
    var numTopos = msgObj.NumTopoId();
    str = String(msgObj.DisplayString);
    if (str.indexOf(message) == 0) {
      messageFound = true;
      break;
    }
  }
  return messageFound;
}
function IcGetFaceAreaAMPUnits(faceId,partId) {

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) {
        if (ds.Tree.Branches.Count)
            branch = ds.Tree.Branches.Item(1);
  }
  if (!branch)
      return;
  var protoGroup = branch.PrototypeGroup;
  var cadUnits = protoGroup.CADUnits;
  var userUnits = ds.UnitSystemID;
  sm.Clear();
  sm.AddToSelection(partId, faceId, false);
  var area = sm.SurfaceAreaofOneSelectedFace(1, userUnits, cadUnits);
  return area;
}
function IcGetEdgeLengthAMPUnits(edgeId,partId) {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) {
        if (ds.Tree.Branches.Count)
            branch = ds.Tree.Branches.Item(1);
  }
  if (!branch)
      return;
  var protoGroup = branch.PrototypeGroup;
  var cadUnits = protoGroup.CADUnits;
  var userUnits = ds.UnitSystemID;
  sm.Clear();
  sm.AddToSelection(partId, edgeId, false);
  var len = sm.LengthofOneSelectedEdge(1, userUnits, cadUnits);
  return len;
}
function IcGetSurfaceAreaAMPUnits(faceId,partId) {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) {
        if (ds.Tree.Branches.Count)
            branch = ds.Tree.Branches.Item(1);
  }
  if (!branch)
      return;
  var protoGroup = branch.PrototypeGroup;
  var cadUnits = protoGroup.CADUnits;
  var userUnits = ds.UnitSystemID;
  sm.Clear();
  sm.AddToSelection(partId, faceId, false);
  var area = sm.SurfaceAreaofOneSelectedFace(1, userUnits, cadUnits);
  return area;
}

function getValveLiftsAttributeString() {
  var i;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_ValveLifts");
  var str="";
  for (i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    str = new String(attr.String);
  }
  return str;
}
function IterativelyMeshPortBottom() {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var i, j, k;

  for (j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (!meshctrl.SubValue) continue; //If suppressed
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    var ctrlName = meshctrl.Name;
    if (ctrlName.indexOf("port") == -1) continue;
    var protos = meshctrl.Prototypes;
    var proto = protos.item(1);
    if (proto.Elements > 0) continue;
    proto = proto.Parent;
    var bodies = proto.Part.BRep.Bodies;
    var protoList = proto.Prototypes;
    var bodyProtoArr = new Array();
    var bodiesArr = new Array();
    sm.Clear();    
    for (k = 1; k <= bodies.Count; ++k) {
      var bodyProto = protoList.item(k);
      var str = bodyProto.Name;
      var pos = str.indexOf("-");
      if (pos < 0) continue;
      str = str.substr(0, pos);
      if (ctrlName.indexOf(str) == -1)
        continue;
      bodyProtoArr.push(bodyProto);
      bodiesArr.push(bodies.item(k).Id);
    }
    if (!bodiesArr.length) continue;
    var prevMethod = meshctrl.SweepShape;
    meshctrl.SweepShape = 0; //Mesh it with Tri
    for (i = 0; i < bodiesArr.length; ++i) {
      sm.Clear();
      sm.AddToSelection(proto.Part.Id, bodiesArr[i], false);
      ICDoModelPreviewMeshBodySelection();
    }
    var max1 = 0., max2 = 0.;
    for (i = 0; i < bodyProtoArr.length; ++i){
      if (bodyProtoArr[i].MeshMetricMax > max1)
        max1 = bodyProtoArr[i].MeshMetricMax;
    }
    meshctrl.SweepShape = prevMethod;
    for (i = 0; i < bodiesArr.length; ++i) {
      sm.Clear();
      sm.AddToSelection(proto.Part.Id, bodiesArr[i], false);
      ICDoModelPreviewMeshBodySelection();
    }
    for (i = 0; i < bodyProtoArr.length; ++i) {
      if (bodyProtoArr[i].MeshMetricMax > max2)
        max2 = bodyProtoArr[i].MeshMetricMax;
    }
    if ((max1 > 0) && (max2 > max1)) {
      meshctrl.SweepShape = 0; //Mesh it with Tri
      for (i = 0; i < bodiesArr.length; ++i) {
        sm.Clear();
        sm.AddToSelection(proto.Part.Id, bodiesArr[i], false);
        ICDoModelPreviewMeshBodySelection();
      }
    }
  }
}
function DisplaySkewnessWarning() {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;
  if (meshGroup.MeshingFailed) return;
  
  var mehctrls = meshGroup.MeshControls;
  var i, j, k;
  var bodiesStr = "";

  for (j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (!meshctrl.SubValue) continue; //If suppressed
    if (meshctrl.ControlType != ds.Script.id_BodyMeshType)
      continue;
    if (meshctrl.Value != 5 && meshctrl.Value != 7) //check for sweep or multizone method
      continue;
    var protos = meshctrl.Prototypes;
    for (i = 1; i <= protos.Count; i++) {
      var proto = protos.item(i);
      if (proto.MeshMetricMax > 0.95) {
        if (bodiesStr != "")
          bodiesStr = bodiesStr + ", ";
        bodiesStr = bodiesStr + proto.Name;
        break;
      }
    }
  }
  if (bodiesStr != "") {
    bodiesStr = "Max Skewness of the following sweepable bodies is more than 0.95 : " + bodiesStr;
    if(g_oApplet)
      g_oApplet.Script.WBScript.Out(bodiesStr, true, "Warning");
    ICEAddMessage(bodiesStr,"Warning");
  }
}
function ICDefineOrResetVlayerChEdgeSizing() {
  var i, j, k, l, str1, str2;
  var nsl, ns;
  var Assys, Assy;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;

  var lStright = IsStraightValveEngine();
  //invalve1-ch, intf-deck-fluid-ch-upper
  var mehctrls = meshGroup.MeshControls;
  var arrNS1 = new Array();
  var arrNS2 = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if (lStright) {
      if (str1.indexOf("-ob-fluid-ch-upper") != -1) {
        arrNS1.push(ns);
      }
      else if (str1.indexOf("intf-deck-fluid-ch-upper") != -1) {
        arrNS2.push(ns);
      }
    }
    else {
      str2 = str1.substring(0, 7);
      if (str2 == "invalve" || str2 == "exvalve") {
        if (str1.indexOf("-ch") != -1)
          arrNS2.push(ns);
      }
      else if (str1.indexOf("-ob-fluid-ch") != -1) {
        arrNS1.push(ns);
      }
    }
  }
  var PartId = 0;
  var intfFaces = new Array();
  var bottomFaces = new Array();
  for (j = 0; j < arrNS1.length; j++) {
    ns = arrNS1[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      var pos = str1.indexOf(";");
      var partid = str1.substring(0, pos);
      if (PartId == 0)
        PartId = partid;
      else if (PartId != partid)
        continue;
      var topid = str1.substring(pos + 1);
      intfFaces.push(topid);
    }
  }
  for (j = 0; j < arrNS2.length; j++) {
    ns = arrNS2[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      var pos = str1.indexOf(";");
      var partid = str1.substring(0, pos);
      if (PartId != partid)
        continue;
      var topid = str1.substring(pos + 1);
      bottomFaces.push(topid);
    }
  }
  if (PartId == 0) return;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var part = Assy.PartById(PartId);

  var intfEdges = new Array();
  var bottomEdges = new Array();
  var intfEdgesFlag = new Array();
  for (j = 0; j < intfFaces.length; ++j) {
    var face = part.BRep.Cell(intfFaces[j]);
    var edges = face.Edges;
    for (i = 1; i <= edges.Count; ++i) {
      intfEdges.push(edges.item(i).Id);
      intfEdgesFlag.push(0);
    }
  }
  for (j = 0; j < bottomFaces.length; ++j) {
    var face = part.BRep.Cell(bottomFaces[j]);
    var edges = face.Edges;
    for (i = 1; i <= edges.Count; ++i) {
      bottomEdges.push(edges.item(i).Id);
    }
  }
  for (j = 0; j < intfEdges.length; ++j) {
    if(intfEdgesFlag[j]) continue;
    for (i = j + 1; i < intfEdges.length; ++i) {
      if (intfEdges[j] == intfEdges[i]) {
        intfEdgesFlag[j] = 1;
        intfEdgesFlag[i] = 1;
        break;
      }
    }
    if (i == intfEdges.length) {
      for (i = 0; i < bottomEdges.length; ++i) {
        if (intfEdges[j] == bottomEdges[i]) {
          intfEdgesFlag[j] = 1;
          break;
        }
      }
    }
  }
  sm.Clear();
  for (j = 0; j < intfEdges.length; ++j) {
    if (intfEdgesFlag[j]) continue;
    sm.AddToSelection(PartId, intfEdges[j], false);
  }
  if (sm.SelectedCount) {
    var minLift = 0.2;
    var attrValue = getMinLift();
    if (attrValue > 0)
      minLift = attrValue;
    var MeshCtrlObj = null;
    str1 = "intf-ch-vlayer-top-edges";
    for (i = 1; i <= mehctrls.Count; i++) {
      meshctrl = mehctrls.item(i);
      if (meshctrl.ControlType != ds.Script.id_Size) continue;
      str2 = new String(meshctrl.Name);
      if ((str2.indexOf(str1) != -1)) {
        MeshCtrlObj = meshctrl;
      }
    }

    if (!MeshCtrlObj) {
      //Body sizing
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        MeshCtrlObj.SizingType = 1; //Hard
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + str1 + ")";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
      }
    }
    else {
      if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
        str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
    }
    MeshCtrlObj.ESize = minLift * 0.6;
  }
}
function IceSetValveBottomSizing()
{
  if(IsStraightValveEngine())
    return;
  if (!ds.Tree.FirstActiveBranch) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;

  var mehctrls = meshGroup.MeshControls;
  
  sm.Clear();
  var faceArr = new Array();
  var facePartArr = new Array();
  ICGetNSSupports("exvalve","-ch",faceArr,facePartArr);
  ICGetNSSupports("invalve","-ch",faceArr,facePartArr);
  if (sm.SelectedCount) {
    var minLift = 0.2;
    var attrValue = getMinLift();
    if (attrValue > 0)
      minLift = attrValue;
    var MeshCtrlObj = null;
    var str1 = "valves-bottom";
    for (var i = 1; i <= mehctrls.Count; i++) {
      meshctrl = mehctrls.item(i);
      if (meshctrl.ControlType != ds.Script.id_Size) continue;
      var str2 = new String(meshctrl.Name);
      if ((str2.indexOf(str1) != -1)) {
        MeshCtrlObj = meshctrl;
      }
    }

    if (!MeshCtrlObj) {
      //Body sizing
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
        var MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + " (" + str1 + ")";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        MeshCtrlObj.ESize = round(ChSize * 1. / 3.);
      }
    }
    else {
      if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
        str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
    }
  }
}
function IsStraightValveEngine() {
  var i, j, k, l, str1, str2;
  var nsl, ns;
  var lReturn = false;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 5);
    if ((str2.indexOf("fluid") != -1) && (str1.indexOf("fluid-ch-upper") != -1)) {
      lReturn = true;
      break;
    }
  }
  return lReturn;
}
function getMinLift() {
  var str1, i, j, str2;
  var meshSize = 0.93;
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_ValveLifts");
  var CA = 0.;
  for (i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.String);
    pos = str.indexOf("MinLift-");
    if (pos > 0) {
      str = str.substring(pos + 8);
      str = str.substring(0, str.length - 1);
      CA = new Number(str);
    }
  }
  return CA;
}
function checkIfHardEdgeSizingIsCausingIssue() {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var MessageDatabase = ds.Tree.MessageDatabase;
  var nb = MessageDatabase.NumMessages;
  var needtoremesh = false;
  for (var i = 0; i < nb; ++i) {
    var msgObj = MessageDatabase.GetMessage(i);
    if (msgObj == null)
      continue;
    var numTopos;
    numTopos = msgObj.NumTopoId();
    if (0 == numTopos)
      continue;
    var part = Assy.PartById(msgObj.GetPartId(0));
    var str = String(part.Name);
    if ((str.indexOf("ch") == -1) && (str.indexOf("piston-layer") == -1)) continue;
    str = String(msgObj.DisplayString);
    if (str.indexOf("The mesher tried to modify the mesh for the following edges that have hard sizing.") != 0)
      continue;

    var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
    if (!meshGroup) break;
    var MeshCtrlObj=null;
    var mehctrls = meshGroup.MeshControls;
    for (var j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      if (meshctrl.ControlType != ds.Script.id_Size) continue;
      var str2 = new String(meshctrl.Name);
      if ((str2.indexOf("intf-ch-vlayer-top-edges") != -1)) {
        MeshCtrlObj = meshctrl;
      }
    }
    if(MeshCtrlObj){
      if (MeshCtrlObj.SizingType == 1) { //Hard
        MeshCtrlObj.SizingType = 0;
        needtoremesh = true;
      }
    }
    break;
  }
  return needtoremesh;
}
function IsAllNSImportedSector() {
  var branch = ds.Tree.FirstActiveBranch;
  var returnVal = true;
  if (!branch)
    return;
  var ns1, ns2, arr;
  var i = 0; j = 0;
  var nsl;
  var allNSImported = true;
  
 
  
  nsl = branch.Components;
  
  if(nsl.Count == 0)
   return false;
   
  var nbDuplicates = getNbDuplicateNS();
  
  if(nbDuplicates == 0)
    return false;
	
  var nsImported= 0;
  var nsManual= 0;
  for (j = nsl.Count; j >= 1; --j) {
     var nsType = 0;
	 ns1 = nsl.item(j);
	 nsType = GetNSType(ns1);
	 
	 if(nsType != 3)
	    continue;
		
	 if (ns1.ImportedFromCAD){
	    nsImported++;
	 }
	 else{
	    nsManual++;
	 }
  }
  
  if(nbDuplicates != nsManual)
     returnVal = false;
  
  return returnVal;
}
function GetNSType(ns){
     var str1 = String(ns.GetUnsuppressedPartTopoPair(0));
     var pos = str1.indexOf(";");
     var partid = str1.substring(0, pos);
     var topid = str1.substring(pos + 1);

     var topoName;
     var topoType = Math.abs(topid & 0xE0000000);
     if (topoType == 0)//vertex
        return 1;
     else if (topoType == 0x40000000)//volume
        return 2;
     else//Face
        return 3;
}
function IsAllNSImported() {
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var ns1, ns2, arr;
  var i = 0; j = 0;
  var nsl;
  var allNSImported = true;

  nsl = branch.Components;
  for (j = nsl.Count; j >= 1; --j) {
    ns1 = nsl.item(j);
    if (!ns1.ImportedFromCAD)
      continue;
    if (ns1.NumInSelection == 0) {
      allNSImported = false;
      break;
    }
  }
  return allNSImported;
}
function DefineOrResetPortInflationCtrl(facesArr, partArr, bodiesArr, wallfaceArr, wallPartArr, wallNSArr) {
  var i, j, k, str1;
  var nsl, ns;
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var found;
  var Assys, Assy;

  if(IsSingleZoneTopo()){
    return;
  }

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  found = false;
  sm.Clear();
  var port;
  var arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-port") != -1)) {
      arr.push(ns);
    }
  }

  //Sweep for bottom ports.
  var pos, partid, partIdInt, part;
  var attrs, attr;
  var face/*IABrFace*/, edges, edge, body, bodies, faces;

  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      break;
    }
    partIdInt = parseInt(partid);
    part = Assy.PartById(partIdInt);
    attrs = part.AttributesByName(1,"ICEngine_SweepSources");
    for (i = 1; i <= attrs.Count; ++i) {
      attr = attrs.item(i);
      face = part.BRep.Cell(attr.TopoId);
      bodies = face.Bodies;
      if (bodies.Count == 2) {
        facesArr.push(face);
        partArr.push(partIdInt);
        bodiesArr.push(bodies.item(1));
        bodiesArr.push(bodies.item(2));
      }
    }
  }

  sm.Clear();
  var oldApproach = getFluentOldApproach();
  if (arr.length && !oldApproach) {
    for (j = 0; j < arr.length; j++) {
      ns = arr[j];
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        for (k = 0; k < partArr.length; ++k) {
          if (partArr[k] != partid) continue;
          if (bodiesArr[2 * k].Id == topid || bodiesArr[2 * k + 1].Id == topid)
            break;
        }
        if (k < partArr.length) continue;

        sm.AddToSelection(partid, topid, false);
      }
    }

    //Inflation
    var MeshCtrlObj = null;
    var mehctrls = meshGroup.MeshControls;
    for (var i = 1; i <= mehctrls.Count; i++) {
      var meshctrl = mehctrls.item(i);
      str1 = new String(meshctrl.Name);
      if (!(meshctrl.ControlType == ds.Script.id_Inflation))
        continue;
      if (str1.indexOf("(port)") != -1) {
        MeshCtrlObj = meshctrl;
        break;
      }
    }    
    if (!MeshCtrlObj) {
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Inflation);
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + " (port)"
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }

    sm.Clear();
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str1 = String(ns.Name);
      if ((str1.indexOf("port") != -1) && (str1.indexOf("fluid-") == -1) && (str1.indexOf("symm-") == -1) && (str1.indexOf("ice-") == -1)) {
        found = true;
        for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
          str1 = String(ns.GetUnsuppressedPartTopoPair(i));
          var pos = str1.indexOf(";");
          var partid = str1.substring(0, pos);
          var topid = str1.substring(pos + 1);
          partIdInt = parseInt(partid);
          part = Assy.PartById(partIdInt);
          face = part.BRep.Cell(topid);
          bodies = face.Bodies;
          if (bodies.Count != 1) continue;
          body = bodies.item(1);
          for (k = 0; k < partArr.length; ++k) {
            if (partArr[k] != partIdInt) continue;
            if (bodiesArr[2 * k].Id == body.Id || bodiesArr[2 * k + 1].Id == body.Id)
              break;
          }
          if (k < partArr.length) {
            wallNSArr.push(j);
            wallfaceArr.push(face.Id);
            wallPartArr.push(partIdInt);
            continue;
          }

          sm.AddToSelection(partid, topid, false);
        }
      }
    }
    if (found)
      MeshCtrlObj.SourceGeometry = sm;
  }
}
function ResetPortNS() {
  var i, j, k, l, str1, str2;
  var ns;

  if (!ds.Tree.FirstActiveBranch) return;
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  var Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  var Assy = Assys.Item(1);

  var arrBodyNS = new Array();
  var arrFaceNS = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-port") != -1)) {
      arrBodyNS.push(ns);
    }
  }
  for (i = 0; i < arrBodyNS.length; ++i) {
    str1 = arrBodyNS[i].Name;
    str1 = str1.substring(6);
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str2 = String(ns.Name);
      if(str1 == str2){
        arrFaceNS.push(ns);
        break;
      }
    }
  }
  if (arrBodyNS.length != arrFaceNS.length)
    return;
  for (i = 0; i < arrBodyNS.length; ++i) {
    ns = arrBodyNS[i];
    var partid = "";
    for (j = 0; j < ns.NumInSelection - ns.NumSuppressedItems; j++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(j));
      var pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      break;
    }
    if (partid == "") continue;
    var partIdInt = parseInt(partid);
    var part = Assy.PartById(partIdInt);
    var faces = part.BRep.Cells(2);
    var facesTag = new Array();
    var face,bodies;
    for (j = 1; j <= faces.Count; ++j) {
      face = faces.item(j);
      bodies = face.bodies;
      if (bodies.Count > 1)//Ignore interior face
        facesTag.push(1);
      else
        facesTag.push(0);
    }
    for (j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      if (ns.Name == arrFaceNS[i].Name) continue;
      for (k = 0; k < ns.NumInSelection - ns.NumSuppressedItems; k++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(k));
        var pos = str1.indexOf(";");
        partid = str1.substring(0, pos);
        if (partIdInt != partid) break;
        var topid = str1.substring(pos + 1);
        for (l = 1; l <= faces.Count; ++l) {
          if (topid == faces.item(l).Id) {
            facesTag[l-1] = 1;
          }
        }
      }
    }
    sm.Clear();
    //Re-assign the supports
    for (j = 1; j <= faces.Count; j++) {
      if (facesTag[j - 1]) continue;
      sm.AddToSelection(partIdInt, faces.item(j).Id, false);
    }
    if (sm.SelectedCount != arrFaceNS[i].NumInSelection) {
      arrFaceNS[i].GeometrySelection = sm;
    }
  }
}
function DoesItContainPorts(){
  var containPorts=0;
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return containPorts;
  var childList = protoGroup.Children;
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    var strName = String(child.Name);
    if ((strName.indexOf("-port") != -1))
      containPorts=1;
  }
  return containPorts;
}

function ICRegenrateSector() {
  //Set the units to mm
  ds.UnitSystemID = 2;
  ICDeleteDuplicateNS();
  DefineSquishSweepMesh(1);
}
function ICDeleteAutomaticPinchControls() {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    //delete only automatic pinches
    if ((meshctrl.ControlType == ds.Script.id_Merge)&&(meshctrl.AutoManualMode==1))
    {
      if (ds.Tree.CanDelete(meshctrl.ID))
        ds.Tree.DeleteItem(meshctrl.ID);
    }
  }
}

//
function DefineEdgeSizingChamber(){

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j, k,isFound;
    var partId;
    
    var EdgeMeshSize; 
    EdgeMeshSize= RefSize/2.0; 
    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
       return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;
            
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
           continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("SrcEdges-Chamber") == -1) continue;
        MeshCtrlObj = meshctrl;
    }
        
    VCellGroup = branch.VirtualCellGroup;
    if (!VCellGroup) return;
    
    vCells = VCellGroup.VirtualSplitEdges;
    
    if (MeshCtrlObj){
      if ( (vCells.Count) && (IsInflationOn==0) ) {
        MeshCtrlObj.ESize = EdgeMeshSize;
        return;
      }
      else if ((MeshCtrlObj.SubValue) && (MeshCtrlObj.State==1) && (IsInflationOn != 0) ) {
          MeshCtrlObj.ESize = EdgeMeshSize; //if meshcontrol has edges selected then return else define edges in sm
          return;
       }
    }
    
    for (i = 1; i <= childList.Count; i++) {
      var child = childList.Item(i);
      if (ds.Script.id_BodyGroup != child.Class) continue;

      var protoList = child.Prototypes;
      if (!protoList || !protoList.count)
          continue;

      for (j = 1; j <= protoList.Count; j++) {
        var proto = protoList.item(j);
        str1 = String(proto.Name);
        sm.Clear();
        var bodies = proto.Part.BRep.Bodies;
        arrPart.push(proto.Part.Id);
        arrName.push(str1);
        arrBody.push(bodies.item(j).Id);
      }
    }
    
    var bodyreq = -1, bodyreqTop = -1, bodyName, bodyPartID;
    for (i = 0; i < arrName.length; ++i) {
      str1 = arrName[i];
      if (str1.indexOf("Chamber-Outer-Bottom") != -1) {
        bodyName = str1;
        bodyreq = arrBody[i];
        bodyPartID = arrPart[i];
      }
      if (str1.indexOf("Chamber-Outer-Top") != -1) {
        bodyName = str1;
        bodyreqTop = arrBody[i];
        bodyPartID = arrPart[i];
        //break;
      }
    }
    if (bodyreq < 0) return;
    
    var faceArr = new Array();
    var facePartArr = new Array();
    var pos;
    var nsl = ds.Tree.FirstActiveBranch.Components;
    if (!nsl) return;

    for (var j = 1; j <= nsl.Count; ++j) {
      ns = nsl.item(j);
      str1 = String(ns.Name);
      if ( (str1.indexOf("ice-cyl-chamber-bottom") != -1)|| (str1.indexOf("ice-cyl-chamber-top")!= -1)){
        for (var i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
          str1 = String(ns.GetUnsuppressedPartTopoPair(i));
          pos = str1.indexOf(";");
          partid = str1.substring(0, pos);
          topid = str1.substring(pos + 1);
          faceArr.push(topid);
          facePartArr.push(partid);
        }
      }
    }
    //get all edges belonging to piston face present in ice-piston NS
    var part=null, face
    var nsEdgeArr = new Array();
    var nsVertexArr = new Array();
    //EdgeArr1 EdgeArr1Vertex EdgeArr2 nsEdgeArrVertex EdgeArr3
    var EdgeArrFromVertex = new Array();
    var EdgeArr = new Array();
    
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
      part = Assy.PartById(facePartArr[i]);
      face = part.BRep.Cell(faceArr[i]);
      edges = face.Edges;
      for (k = 1; k <= edges.Count; ++k){
        nsEdgeArr.push(edges.item(k));
      }
    }
    for (i = 0; i < nsEdgeArr.length; ++i) {
      edge = nsEdgeArr[i];
      var vertex = edge.StartVertex;
      nsVertexArr.push(vertex);         
      edges = vertex.Edges;
      for (k = 1; k <= edges.Count; ++k){
        edge = edges.item(k);
        bodies = edge.Bodies;
        EdgeArrFromVertex.push(edges.item(k));
      }
      edge = nsEdgeArr[i];
      vertex = edge.EndVertex;
      nsVertexArr.push(vertex);
      edges = vertex.Edges;
      for (k = 1; k <= edges.Count; ++k){
        edge = edges.item(k);
        bodies = edge.Bodies;
        EdgeArrFromVertex.push(edges.item(k));
            
      }
    }
    for (i = 0; i < EdgeArrFromVertex.length; ++i) {
      isFound = false;
      edge= EdgeArrFromVertex[i];
      bodies = edge.Bodies;
      for (j = 0; j < nsEdgeArr.length; ++j) {
        if (EdgeArrFromVertex[i].id == nsEdgeArr[j].id ) { //remove NS edges from this array
          isFound = true;
          break;
        }
      }
      if (isFound) continue;
      if (bodies.Count == 1) {
        if ((bodies.item(1).Id == bodyreq) || (bodies.item(1).Id == bodyreqTop)){  //this is for vertical edges of piston-body that we have to eliminate
          isFound = false;  
          for (j = 0; j < EdgeArr.length; ++j) {  //this is to remove duplicate edges
            if (EdgeArrFromVertex[i].id == EdgeArr[j].id ) {
              isFound = true;
              break;
            }
          }
          if (!isFound)
            EdgeArr.push(EdgeArrFromVertex[i]);
        }  
      }
      if (bodies.Count == 2) {
        if ((bodies.item(1).Id == bodyreq) ||(bodies.item(2).Id == bodyreq)){
          isFound = false;  
          for (j = 0; j < EdgeArr.length; ++j) {
            if (EdgeArrFromVertex[i].id == EdgeArr[j].id ) {
              isFound = true;
              break;
            }
          }
          if (!isFound)
            EdgeArr.push(EdgeArrFromVertex[i]);
        }
      }
    }
    //vritual splitting of edges
    
   
    if (IsInflationOn == 0) {
      sm.Clear();
      var faces, edges;
      var finalEdgeArr = new Array();
      for (i = 0; i < EdgeArr.length; ++i) {
        var beforeSplitEdgeArr = new Array();
        var afterSplitEdgeArr = new Array();
        edge = EdgeArr[i];
        faces = edge.Faces;
        edges= faces.item(1).Edges;
        for (k = 1; k <= edges.Count; ++k) {
          beforeSplitEdgeArr.push(edges.item(k));
        }
        
        vertex = edge.StartVertex;
        sm.AddToSelection(bodyPartID, EdgeArr[i].id, false);
        var vcell = ICEVirtualSplitEdge();
        isFound= false;
        for (j = 0; j < nsVertexArr.length; ++j){
          if(vertex==nsVertexArr[j]) {
            isFound = true;
            break;
          }
        }
        if (vcell)
          if(!isFound)
            vcell.SplitEdgeRatio = 0.989;
          else 
            vcell.SplitEdgeRatio = 0.011;
        edges= faces.item(1).Edges;
        for (k = 1; k <= edges.Count; ++k) {
          afterSplitEdgeArr.push(edges.item(k));
        }
        
        for (j = 0; j < afterSplitEdgeArr.length; ++j){
          isFound = false; 
          for (l = 0; l < beforeSplitEdgeArr.length; ++l){
            if (afterSplitEdgeArr[j].id == beforeSplitEdgeArr[l].id) {
              isFound = true;
              break;
            }
          }
          if (!isFound)
            finalEdgeArr.push(afterSplitEdgeArr[j]);
        }  
      }
    
      sm.Clear();
       
      for (i = 0; i < finalEdgeArr.length; i=i+2){
        if (finalEdgeArr[i].Length > finalEdgeArr[i+1].Length)
           sm.AddToSelection(bodyPartID, finalEdgeArr[i].id, false);
        else 
           sm.AddToSelection(bodyPartID, finalEdgeArr[i+1].id, false);
   
      }
    }
    else {
      sm.Clear();
      for (j = 0; j < EdgeArr.length; ++j) {
        sm.AddToSelection(bodyPartID, EdgeArr[j].id, false);
    }
    
    }
   // defining edge sizing 
    if (sm.SelectedCount) {
      if (!MeshCtrlObj) {
          MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
          if ((MeshCtrlObj) && (MeshCtrlObj.SubValue)){
             MeshCtrlObj.Name = MeshCtrlObj.Name + "(SrcEdges-Chamber)";
             MeshCtrlObj.ESize = EdgeMeshSize;
             MeshCtrlObj.SizingType = 1; //Hard
             MeshCtrlObj.SourceTargetSelection = 1;
             MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
             ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
          }
      }
      else {
            var str1 = MeshCtrlObj.Name;
            MeshCtrlObj.ESize = EdgeMeshSize;
            MeshCtrlObj.GeometrySelection = sm;
            MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
       }
    }
}

function DefinePistonInflationEdgeSizing() {

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;

    
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;
        
    var faceMeshSize; 
    faceMeshSize = RefSize;
    faceMeshSize= faceMeshSize/2.0;

    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            bodyPartID = proto.Part.Id;
            break;

        }
    }

    var attrs, attr;
    var face, edges, edge, body, bodies, faces;
    var part, partIdInt;
    partIdInt = parseInt(bodyPartID);
    part = Assy.PartById(partIdInt);
    sm.Clear();
    var creviceEdgeArr = new Array();
    var attrs = part.AttributesByName(1,"ICEngine_Crevice_Thickness");
    for (j = 1; j <= attrs.Count; ++j) {
        var attr = attrs.item(j);
        var partid = bodyPartID;
        var topid = attr.TopoId;
        creviceEdgeArr.push(topid);
        //sm.AddToSelection(partid, topid, false);
    }
    
    var inflationEdgeArr = new Array();
    var attrs = part.AttributesByName(1,"ICEngine_Piston_Inflation");
    for (i = 1; i <= attrs.Count; ++i) {
        var attr = attrs.item(i);
        var partid = bodyPartID;
        var topid = attr.TopoId;
        inflationEdgeArr.push(topid);
        isFound = false;
        for (var j = 0; j < creviceEdgeArr.length; ++j) {
          if (topid == creviceEdgeArr[j]){
            isFound = true;
           break;
         }
       }
       if (!isFound)
       sm.AddToSelection(bodyPartID, topid, false);
        //sm.AddToSelection(partid, topid, false);
    }

    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj = null;
    for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
            continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("PistonInflationOuter") == -1) continue;
          MeshCtrlObj = meshctrl;
    }

    if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
        if (MeshCtrlObj) {
            MeshCtrlObj.Name = MeshCtrlObj.Name + " (PistonInflationOuter) ";
            MeshCtrlObj.ESize = faceMeshSize;
            MeshCtrlObj.SizingType = 1; //Hard
            MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
            ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
           
        }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        MeshCtrlObj.ESize = faceMeshSize;
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
    }
}
function IsVlayerTwoPlaneSliceApproach() {
  var lReturn=false;

  if (!ds.Tree.FirstActiveBranch) return;
  var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  var Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  var Assy = Assys.Item(1);

  var Parts = Assy.Parts(true);
  for (var k = 1; k <= Parts.Count; ++k) {
    var Part = Parts.Item(k);
    var str1 = String(Part.Name);
    var pos = str1.indexOf("-vlayer");
    if (pos== -1)
      continue;
    sm.Clear();
    var attrs = Part.AttributesByName(1,"ICEngine_SweepSources");
    if(Part.BRep.Bodies.Count ==  attrs.Count)
      lReturn = true;
    break;
  }
  return lReturn;
}

function ICECreateVirtualEdges(doForChLowerOnly,regeneration) {
  var protoGroup, childList, proto, child, protoList;
  protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  branch = ds.Tree.FirstActiveBranch;
  VCellGroup = branch.VirtualCellGroup;
  if (!VCellGroup)
    ds.Script.doInsertVTGroup(ds.Tree.FirstActiveBranch.Model);

  childList = protoGroup.Children;
  for (var i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);

    if (ds.Script.id_BodyGroup != child.Class) continue;

    var partName = String(child.Name);
    if(doForChLowerOnly){
      if(partName.indexOf("ch-lower") == -1)
        continue;
    }
    else{
        if ((partName.indexOf("-vlayer") == -1) && (partName.indexOf("-ib") == -1) && (partName.indexOf("-layer") == -1)&& (partName.indexOf("-port") == -1)) {
            continue;
        }
    }
    protoList = child.Prototypes;
    if(!protoList.Count) continue;
    proto = protoList.Item(1);
    var edges = proto.Part.BRep.Cells(1);
    //for piston-layer part, only merge layer cylinder body edges
    var bodies = proto.Part.BRep.Bodies;
    if(partName.indexOf("-layer") != -1){
      for(var k=1;k<=protoList.Count;++k){
        var bodyName = protoList.Item(k).Name;
        if(bodyName.indexOf("layer")!=-1){
          edges = bodies.Item(k).Edges;
          break;
        }
      }
    }
    var trgEdges = new Array();
    //Only merge port bottom edges, as we are defining sweep there
    if(partName.indexOf("-port") != -1){
      for(var k=1;k<=protoList.Count;++k){
        var bodyName = protoList.Item(k).Name;
        if(bodyName.indexOf("-port")!=-1){
          edges = bodies.Item(k).Edges;
          for(var j=1;j<=edges.Count;++j){
            trgEdges.push(edges.Item(j));
          }
        }
      }
    }
    else{
      for (var k = 1; k <= edges.Count; k++) {
        trgEdges.push(edges.item(k));
      } 
    }
    var edge,faces;
    //This array stores edge ids
    var edgeArr = new Array();
    //This array stores sorted face list ids for each edge respectively
    var faceArr = new Array();
    //This array stores number of faces per edges and its size is edge array size plus 1
    var faceIndexArr = new Array();
    faceIndexArr.push(0);
    var index=0;
    for (var k = 0; k < trgEdges.length; k++) {
      edge = trgEdges[k];
      if(regeneration){
        //if the edge created by virtual split, we should not merge the edge created by vt. 
        //because for cold flow tutorial Meshing hangs in regenration because Splitting virtual edges
        if (edge.CurveType == 8)//kABrCurveFaceted
          continue;
      }
      edgeArr.push(edge.Id);
      faces = edge.Faces;
      var faceArrTmp =new Array();
      for(var j=1; j<= faces.Count; j++)
        faceArrTmp.push(faces.Item(j).Id);
      sortInputArray(faceArrTmp);
      faceArr = faceArr.concat(faceArrTmp);
      index += faces.Count;
      faceIndexArr.push(index);
    }
    var searchedArr = new Array();
    for (var k = 0; k < edgeArr.length; k++)
      searchedArr.push(false);
    //The aim is to find merge the edges which has same set of faces
    for (var k = 0; k < edgeArr.length; k++) {
      if(searchedArr[k]) continue;
      sm.Clear();
      for (var l = k+1; l < edgeArr.length; l++) {
        if((faceIndexArr[k+1]-faceIndexArr[k])!=(faceIndexArr[l+1]-faceIndexArr[l]))
          continue;
        if((faceIndexArr[k+1]-faceIndexArr[k]) == 2){
          if( (faceArr[faceIndexArr[k]] == faceArr[faceIndexArr[l]]) &&
              (faceArr[faceIndexArr[k]+1] == faceArr[faceIndexArr[l]+1])){
            searchedArr[l]=true;
            sm.AddToSelection(proto.Part.Id, edgeArr[l], false);
          }
        }
        else if((faceIndexArr[k+1]-faceIndexArr[k]) == 3){
          if( (faceArr[faceIndexArr[k]] == faceArr[faceIndexArr[l]]) &&
             (faceArr[faceIndexArr[k]+1] == faceArr[faceIndexArr[l]+1])&&
              (faceArr[faceIndexArr[k]+2] == faceArr[faceIndexArr[l]+2])){
            searchedArr[l]=true;
            sm.AddToSelection(proto.Part.Id, edgeArr[l], false);
          }
        }
        else if((faceIndexArr[k+1]-faceIndexArr[k]) == 4){
          if( (faceArr[faceIndexArr[k]] == faceArr[faceIndexArr[l]]) &&
              (faceArr[faceIndexArr[k]+1] == faceArr[faceIndexArr[l]+1])&&
              (faceArr[faceIndexArr[k]+2] == faceArr[faceIndexArr[l]+2])&&
              (faceArr[faceIndexArr[k]+3] == faceArr[faceIndexArr[l]+3])){
            searchedArr[l]=true;
            sm.AddToSelection(proto.Part.Id, edgeArr[l], false);
          }
        }
      }
      if(sm.SelectedCount>0){
        sm.AddToSelection(proto.Part.Id, edgeArr[k], false);
        if(sm.SelectedCount > 1)
          ICEAddVirtualFace();
      }
    }
  }
}

function ICPortSizing(IsRegen) {
  var branch = ds.Tree.FirstActiveBranch;
  var ns, name, str1, str, found, chNs = null;
  var i, j = 0;
  var partid, topid, pos;

  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;

  var arr = new Array();
  var childList = protoGroup.Children;
  var i, j;
  for (i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;
    sm.Clear();
    for (j = 1; j <= protoList.Count; j++) {
      var proto = protoList.item(j);
      str1 = String(proto.Name);
      var bodies = proto.Part.BRep.Bodies;
      //DE64955: adding all chmaber bodies to BOdySizing definition for cutcell and only chanber body for Hybrid 
      if (MeshType == 1) {
        if ((str1.indexOf("-Port") != -1) )
            sm.AddToSelection(proto.Part.Id, bodies.item(j).Id, false);
      }
    }
    if(sm.SelectedCount){
      var meshGroup = branch.MeshControlGroup;
      //If it already contains mesh size, return
      var mehctrls = meshGroup.MeshControls;
      var meshctrl;
      var MeshCtrlObj = null;
      for (var j = 1; j <= mehctrls.Count; j++) {
        meshctrl = mehctrls.item(j);
        if (meshctrl.ControlType != ds.Script.id_Size)
          continue;
        var str = new String(meshctrl.Name);
        if (str.indexOf("(PortBody)") != -1) {
          MeshCtrlObj = meshctrl;
          break;
        }
      }
      if (!MeshCtrlObj) {
        MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
        if (MeshCtrlObj) {
          MeshCtrlObj.ESize = ChSize;
          MeshCtrlObj.SizingTransition = ChGrowthRate;
          MeshCtrlObj.Name = MeshCtrlObj.Name + " (PortBody)";
          MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
          ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        }
      }
      else {
        if (sm.SelectedCount != MeshCtrlObj.GeometryNum) {
          var str1 = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
        }
      
        if (!IsRegen) {
          if (meshGroup.AssemblyMeshingMethod)//cutcell
            meshctrl.SizingTransition = 0;
          else
            meshctrl.SizingTransition = ChGrowthRate;
          meshctrl.ESize = ChSize;
        }
      }
      break;
    }
  }
}

function ICDeleteBodySizePort() {
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch) return;
  var meshGroup = branch.MeshControlGroup;

  //If it already contains mesh size, return
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  for (var j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    var str = new String(meshctrl.Name);
    if (str.indexOf("(PortBody)") != -1) {
      if (ds.Tree.CanDelete(meshctrl.ID))
        ds.Tree.DeleteItem(meshctrl.ID);
      break;
    }
  }
}

/////////////////////////////////////
//IC Utility Methods
/////////////////////////////////////
//Utility
function sortInputArray(InpArray){
  for(var j=0; j< InpArray.length; ++j){
    for(var l=j+1; l< InpArray.length; ++l){
      if(InpArray[j] > InpArray[l]){
        var tmp = InpArray[j];
        InpArray[j] = InpArray[l];
        InpArray[l] = tmp;
      }
    }
  }
}
//Utility
function ICGetNSSupports(startsWith,intfNs,topoArr,partArr){
  var nsl, ns;
  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var nsArr=new Array();
  
  var found=false;
  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    var str1 = String(ns.Name);
    if((startsWith!="")&&(str1.indexOf(startsWith) != 0))
        continue;
    if ((intfNs!="")&&(str1.indexOf(intfNs) == -1))
      continue;
    nsArr.push(ns);
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      var pos = str1.indexOf(";");
      var partid = str1.substring(0, pos);
      partArr.push(partid);
      var topid = str1.substring(pos + 1);
      topoArr.push(topid);
      sm.AddToSelection(partid, topid, false);
    }
  }
  return nsArr;
}
//Utility
function FindInArray(trgArray,item){
  var lreturn=-1;
  for (var i = 0; i < trgArray.length; ++i) {
    if(trgArray[i]==item){
      lreturn=i;
      break;
    }
  }
  return lreturn;
}
//Utility
function FindDoubleInArray(trgArray,item,percentageTolerance){
  var lreturn=-1;
  if(!percentageTolerance)
    percentageTolerance = 0.1;
  for (var i = 0; i < trgArray.length; ++i) {
    if(IcAreDoublesEqual(trgArray[i],item,percentageTolerance)){
      lreturn=i;
      break;
    }
  }
  return lreturn;
}
//Utility
function IcAreDoublesEqual(firstVal,seconVal,percentageTolerance){
  if(!percentageTolerance)
    percentageTolerance = 0.1;
  var areSame=false;
  if(seconVal == 0){
    if(firstVal == 0)
      areSame=true;
  }
  else{
    var divison = firstVal/seconVal;
    if( (divison > (1-(percentageTolerance/100))) && (divison < (1+(percentageTolerance/100))) ){
      areSame=true;
    }
  }
  return areSame;
}
function writeMeshSettings(path) {
    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
    var textStream = fileSys.CreateTextFile(path, true);
    var line="reference_mesh_size "+new String(getPanelRefSize()/1000.);//write in meters
    textStream.WriteLine(line);
    textStream.Close();
}
//Utility
function getPanelRefSize(){
  var size=getMeshSize();
  ICConvertPanelStringFormat();
  var panel = ICGetPanelField("RefSize");
  if (panel != "") {
    size=new Number(panel);
  }
  else{
    size = round(getMeshSize());
  }
  return size;
}
//Utility
var prevTime=null;
function IceGetTimeElasped(){
   var elapsed=0;
   var curTime = new Date();
   if(prevTime!=null){
     elapsed = (curTime.getTime() - prevTime.getTime() ) / 1000 ; 
   }
   prevTime = curTime;
   return elapsed;
}
//Utility
function IceHideAllParts(){
  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;

  //Hide everthing
  if (typeof (ds.Script.lv) != "undefined")
    ds.Script.hideAllParts( childList );
  else{
    var i;
    var j;

    for(i=1; i<=childList.Count; i++)
    {
        var proto;
        var child = childList.Item(i);

        if( ds.Script.id_Prototype == child.Class )
        {
            proto = child;
            if(!proto.Suppressed && !proto.Hidden)
            {
                proto.Hidden = true;
                ds.Script.updateOneNodeState( proto.ID )
            }
        }
        else if( ds.Script.id_BodyGroup == child.Class )
        {
            var protoList = child.Prototypes;
            for( var j=1; j<=protoList.Count; j++ )
            {
                proto = protoList(j);
                if(!proto.Suppressed && !proto.Hidden)
                {
                    proto.Hidden = true;
                    ds.Script.updateOneNodeState( proto.ID )
                }
            }
        }
    }
  }
}
//Utility
function IceShowAllParts(){
  if (typeof (ds.Script.lv) != "undefined")
    ds.Script.doShowAllParts();
  else{
    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i;
    var count = childList.Count;
    for(i=1; i<=count; i++)
    {
      var child = childList.Item(i);

      if( ds.Script.id_Prototype == child.Class )
      {
        if(!child.Suppressed && child.Hidden)
        {
          // only update node state if it changes (improves time dramatically for large models)
          child.Hidden = false;

          ds.Script.updateOneNodeState( child.ID );
        }
      }
      else if( ds.Script.id_BodyGroup == child.Class )
      {
        var protoList = child.Prototypes;
        var protoCount = protoList.Count;
        for( var j=1; j<=protoCount; j++ )
        {
          var proto = protoList(j);
          if(!proto.Suppressed && proto.Hidden)
          {
            // only update node state if it changes (improves time dramatically for large models)
            proto.Hidden = false;

            ds.Script.updateOneNodeState( proto.ID );
              if( j == protoCount )
                ds.Script.updateOneNodeState( child.ID );
          }
        }
      }
    }
  }
}

function IceShowBodyByName(bodyName){
  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    for (var j = 1; j <= protoList.count; ++j){
      var proto = protoList.item(j);
      var str1=String(proto.Name);
      if (str1.indexOf(bodyName) != -1){
        if(proto.Hidden)
          proto.Hidden = false;
      }
    }
  }
}
function IceShowPortBottom(){
  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var reqProtoArr = new Array();
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    var str1 = String(child.Name);
    if (str1.indexOf("-port-") != -1) {
      for (var j = 1; j <= protoList.count; ++j)
        reqProtoArr.push(protoList.item(j));
    }
  }
  for (var i = 0; i < reqProtoArr.length; ++i) {
    proto = reqProtoArr[i];
    var str1=String(proto.Name);
    if (str1.indexOf("-port-") != -1){
      if(proto.Hidden)
        proto.Hidden = false;
    }
  }
}
function IceStoreTheOriginalHideSuppressStates(hideStates,suppressStates){
  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var reqProtoArr = new Array();
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;
    for (var j = 1; j <= protoList.count; ++j){
      proto=protoList.item(j);
      hideStates.push(proto.Hidden);
      suppressStates.push(proto.Suppressed);
    }
  }
}
function IceRestoreTheOriginalHideSuppressStates(hideStates,suppressStates){
  var protoGroup = ICGetProtoGroup();
  var childList = protoGroup.Children;
  var reqProtoArr = new Array();
  var index1=0,index2=0;
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    var protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;
    for (var j = 1; j <= protoList.count; ++j){
      proto=protoList.item(j);
      if(index1<hideStates.length){
        proto.Hidden = hideStates[index1];
        index1++;
      }
      if(index2<suppressStates.length){
        proto.Suppressed = suppressStates[index2];
        index2++;
      }
    }
  }
}
function ICDefineFaceSizingCreviceInterface(){
    

    var protoGroup = ICGetProtoGroup();
    var childList = protoGroup.Children;
    var i, j;
    var partId;
  
    var Assys = pm.assemblies;
    if (Assys.Count < 1)
        return;

    var Assy = Assys.Item(1);

    var arrName = new Array();
    var arrBody = new Array();
    var arrPart = new Array();

    var MeshCtrlGrpNode;
    var branch = ds.Tree.FirstActiveBranch;
    if (!branch)
        return;
    var meshGroup = branch.MeshControlGroup;
    if (!meshGroup)
        return;
//getting all bodies present under "ch" part
    for (i = 1; i <= childList.Count; i++) {
        var child = childList.Item(i);
        if (ds.Script.id_BodyGroup != child.Class) continue;

        var protoList = child.Prototypes;
        if (!protoList || !protoList.count)
            continue;

        for (j = 1; j <= protoList.Count; j++) {
            var proto = protoList.item(j);
            str1 = String(proto.Name);
            sm.Clear();
            if ((str1.indexOf("ch") != -1) || (str1.indexOf("piston-body") != -1)) {
            var bodies = proto.Part.BRep.Bodies;
            arrPart.push(proto.Part.Id);
            arrName.push(str1);
            arrBody.push(bodies.item(j).Id);
            }
        }
    }
   
    var faceArr = new Array();
    var facePartArr = new Array();
    ICGetNSSupports("","intf-crevice-on-piston",faceArr,facePartArr);
    if (!faceArr.length) return;

//getting all faces belonging to NS "intf-crevice-on-piston" and present in bodies of "crevice" part
    var part, face;
    sm.Clear();
    for (var i = 0; i < faceArr.length; ++i) {
        part = Assy.PartById(facePartArr[i]);
        face = part.BRep.Cell(faceArr[i]);

        for (j = 0; j < arrName.length; ++j) {
          if (facePartArr[i] != arrPart[j]) 
            continue;
          var bodies = face.Bodies;
          if (bodies.Count == 2)
            continue;
          if (bodies.item(1).Id == arrBody[j])
            sm.AddToSelection(arrPart[j], face.Id, false);
           
        }
    } 

    // defining face sizing 
    if (sm.SelectedCount) {
      var mehctrls = meshGroup.MeshControls;
      var meshctrl;
      var MeshCtrlObj=null;
      for (var j = 1; j <= mehctrls.Count; j++) {
          meshctrl = mehctrls.item(j);
          if (meshctrl.ControlType != ds.Script.id_Size)
              continue;
          var str = new String(meshctrl.Name);
          if (str.indexOf("intf-crevice-piston") == -1) continue;
            MeshCtrlObj = meshctrl;
      }
      
      if (!MeshCtrlObj) {
          MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size);
          if (MeshCtrlObj) {
              MeshCtrlObj.Name = MeshCtrlObj.Name + "(intf-crevice-piston)";
              MeshCtrlObj.SizingType = 1; //Hard
              MeshCtrlObj.SourceTargetSelection = 1;
              MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
              ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
          }
      }
      else {
          var str1 = MeshCtrlObj.Name;
          MeshCtrlObj.GeometrySelection = sm;
          MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
      }
      MeshCtrlObj.ESize = IntfCrevicePiston ;
   }
}
function DoesItContainCrevice(){
  var containCrevice=0;
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return containCrevice;
  var childList = protoGroup.Children;
  for (var i = 1; i <= childList.Count; i++) {
    var child = childList.Item(i);
    var strName = String(child.Name);
    if ((strName.indexOf("crevice") != -1))
      containCrevice=1;
  }
  return containCrevice;
}
//Merge the thin faces in the port bottom created during mid-radius slice
function ICECreateVCPortBottomThinFaces() {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var i,j,k;

  var arr = new Array();
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    str2 = str1.substring(0, 7);
    if ((str2.indexOf("fluid-") != -1) && (str1.indexOf("-port") != -1)) {
      arr.push(ns);
    }
  }
  //Sweep for bottom ports.
  var pos, partid, partIdInt, part;
  var attrs, attr;
  var srcFace, face/*IABrFace*/, edges, edge, body, bodies,bodies1, faces;
  var srcFaces, srcParts, srcBodies;
  srcFaces = new Array();
  srcParts = new Array();
  srcBodies = new Array();

  //Identify the source faces
  for (j = 0; j < arr.length; j++) {
    ns = arr[j];
    for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
      str1 = String(ns.GetUnsuppressedPartTopoPair(i));
      pos = str1.indexOf(";");
      partid = str1.substring(0, pos);
      break;
    }
    partIdInt = parseInt(partid);
    part = Assy.PartById(partIdInt);
    attrs = part.AttributesByName(1,"ICEngine_SweepSources");
    for (i = 1; i <= attrs.Count; ++i) {
      attr = attrs.item(i);
      srcFace = part.BRep.Cell(attr.TopoId);
      srcFaces.push(srcFace);
      bodies = srcFace.Bodies;
      if (bodies.Count == 2) {
        srcParts.push(partIdInt);
        srcParts.push(partIdInt);
        srcBodies.push(bodies.item(1));
        srcBodies.push(bodies.item(2));
        faces = bodies.item(1).Faces;
        for (k = 1; k <= faces.Count; ++k) {
          face = faces.item(k);
          if (srcFace.Id == face.Id) continue;
          bodies1 = face.Bodies;
          if (bodies1.Count != 2) continue;
          if (((bodies.item(1).Id == bodies1.item(1).Id) && (bodies.item(2).Id == bodies1.item(2).Id))
                || ((bodies.item(2).Id == bodies1.item(1).Id) && (bodies.item(1).Id == bodies1.item(2).Id))) {
            srcFaces.push(face);
            break;
          }
        }
      }
    }
  }
  if(srcFaces.length != srcBodies.length) 
    return;
  var nbPortBottoms = srcBodies.length/2;
  var portNsFaces=new Array(nbPortBottoms);
  for (j = 0; j < nbPortBottoms; ++j) {
    portNsFaces[j] = new Array();
  }
//Get port ns faces
  for (j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    str1 = String(ns.Name);
    if ((str1.indexOf("port") != -1) && (str1.indexOf("fluid-") == -1) && (str1.indexOf("symm-") == -1) && (str1.indexOf("ice-") == -1)) {
      found = true;
      for (i = 0; i < ns.NumInSelection - ns.NumSuppressedItems; i++) {
        str1 = String(ns.GetUnsuppressedPartTopoPair(i));
        var pos = str1.indexOf(";");
        var partid = str1.substring(0, pos);
        var topid = str1.substring(pos + 1);
        partIdInt = parseInt(partid);
        part = Assy.PartById(partIdInt);
        face = part.BRep.Cell(topid);
        bodies = face.Bodies;
        if (bodies.Count != 1) continue;
        body = bodies.item(1);
        var foundIndex=-1;
        for (k = 0; k < nbPortBottoms; ++k) {
          if (srcParts[2*k] != partIdInt) continue;
          if (srcBodies[2 * k].Id == body.Id || srcBodies[2 * k + 1].Id == body.Id){
            foundIndex = k;
            break;
          }
        }
        if (foundIndex > -1) {
          portNsFaces[foundIndex].push(face);
        }
      }
    }
  }
  for (i = 0; i < nbPortBottoms; ++i) {
    var edges,edge,faces,face;
    var trgEdges = new Array();
    edges = srcFaces[2*i].Edges;
    //get edges corresponding to port faces
    for(j=1; j<= edges.Count; ++j){
      edge = edges.Item(j);
      faces = edge.Faces;
      for(k=1; k<= faces.Count; ++k){
        face = faces.Item(k);
        if(srcFaces[2*i].Id == face.Id) 
          continue;
        if(FindInArrayUsingId(portNsFaces[i],face) > -1){
          trgEdges.push(edge);
          break;
        }
      }
    }
    //check for thin edges (less than min size) and merge with adjacent faces
    var thinEdges = new Array();
    for(j = 0; j < trgEdges.length; ++j){
      if(IcGetEdgeLengthAMPUnits(trgEdges[j].Id,srcParts[2*i]) < (0.5 * MinMeshSize))
        thinEdges.push(trgEdges[j]);
    }
    var edgesToMerge = new Array();
    //For each thin edge, find the adjacent edge to be merged with
    for(j = 0; j < thinEdges.length; ++j){
      for(k = 0; k < trgEdges.length; ++k){
        if(FindInArrayUsingId(thinEdges,trgEdges[k]) > -1)
          continue;
        if(AreTheVertexEqual(trgEdges[k].StartVertex,thinEdges[j].StartVertex)||
           AreTheVertexEqual(trgEdges[k].StartVertex,thinEdges[j].EndVertex)||
           AreTheVertexEqual(trgEdges[k].EndVertex,thinEdges[j].StartVertex)||
           AreTheVertexEqual(trgEdges[k].EndVertex,thinEdges[j].EndVertex)){
          edgesToMerge.push(thinEdges[j]);
          edgesToMerge.push(trgEdges[k]);
          break;
        }
      }
    }
    for(j = 0; j < (edgesToMerge.length/2); ++j){
      var body1Faces=new Array();
      var body2Faces=new Array();
      for(var m=0; m<2; m++){
        faces = edgesToMerge[2*j+m].Faces;
        for(k = 1; k <= faces.Count; ++k){
          face = faces.Item(k);
          bodies = face.Bodies;
          if(bodies.Count > 1)
            continue;
          if(srcBodies[2*i].Id == bodies.Item(1).Id){
            body1Faces.push(face.Id);
          }
          else if(srcBodies[2*i+1].Id == bodies.Item(1).Id){
            body2Faces.push(face.Id);
          }
        }
      }
      if(body1Faces.length > 1){
        sm.Clear();
        for(j=0; j<body1Faces.length;++j)
          sm.AddToSelection(srcParts[2*i], body1Faces[j], false);
        ICEAddVirtualFace();
      }
      if(body2Faces.length > 1){
        sm.Clear();
        for(j=0; j<body2Faces.length;++j)
          sm.AddToSelection(srcParts[2*i], body2Faces[j], false);
        ICEAddVirtualFace();
      }
    }
  }
}
//Merge the thin faces in the port bottom created during mid-radius slice
function ICECreateVCforDomeSliverFaces(updateNS) {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  
  var nsTopoArr=new Array(),nsPartArr=new Array();
  sm.Clear();
  var nsArr = ICGetNSSupports("cyl-head","",nsTopoArr,nsPartArr);
  if(nsPartArr.length == 0)
    return;
  var part = Assy.PartById(nsPartArr[0]);
  var slivers = new Array();
  for(var i=0; i< nsTopoArr.length; ++i)
  {
    var area = IcGetSurfaceAreaAMPUnits(nsTopoArr[i],nsPartArr[i]);
    var face = part.BRep.Cell(nsTopoArr[i]);
    var edges = face.edges;
    var maxEdgeLegth=0;
    for(var j=1; j<= edges.Count; ++j)
    {
      var len = IcGetEdgeLengthAMPUnits(edges.Item(j).Id,nsPartArr[i]);
      if( len > maxEdgeLegth)
        maxEdgeLegth = len;
    }
    if(area < maxEdgeLegth*0.05)
      slivers.push(nsTopoArr[i]);
  }
  var vcFaceArr= new Array(), nbFacesArr= new Array();
  for(var i=0; i< slivers.length; ++i)
  {
    if(FindInArray(vcFaceArr,slivers[i]) != -1)
      continue;
    sm.Clear();
    sm.AddToSelection(part.Id, slivers[i], false);
    sm.floodSelect(45.);
    if ((sm.SelectedCount <= 1)||(sm.SelectedCount > nsPartArr.length/2)) continue;
    var partOfIntialSetOfFaces=true;
    for (var j = 1; partOfIntialSetOfFaces && (j <= sm.SelectedCount); j++) {
      var topoId = sm.SelectedEntityTopoID(j);
      if(FindInArray(nsTopoArr,topoId) == -1)
        partOfIntialSetOfFaces=false;
    }
    if(!partOfIntialSetOfFaces)
      continue;
    for (var j = 1; j <= sm.SelectedCount; j++) {
      var topoId = sm.SelectedEntityTopoID(j);
      if(FindInArray(vcFaceArr,topoId) == -1)
        vcFaceArr.push(topoId);
    }
    nbFacesArr.push(vcFaceArr.length);
  }
  var refArr=new Array();
  var j=0;
  for(var i=0; i<nbFacesArr.length; ++i)
  {
    sm.Clear();
    for(; j < nbFacesArr[i];++j)
      sm.AddToSelection(part.Id, vcFaceArr[j], false);
    var vCell=null;
    if (sm.SelectedCount > 1)
      vCell = ICEAddVirtualFace();
    if (vCell && vCell.RefId)
      refArr.push(vCell.RefId);
  }
  if(updateNS){
    sm.Clear();
    for (i = 0; i < nsTopoArr.length; i++) {
      sm.AddToSelection(nsPartArr[i], nsTopoArr[i], false);
    }
    for (i = 0; i < refArr.length; i++) {
      var topoId = part.GetTopoId(refArr[i]);
      sm.AddToSelection(part.Id, topoId, false);
    }
    if(refArr.length && nsArr.length)
      nsArr[0].GeometrySelection = sm;
  }
}
//Utility
function FindInArrayUsingId(trgArray,item){
  var lreturn=-1;
  for (var i = 0; i < trgArray.length; ++i) {
    if(trgArray[i].Id==item.Id){
      lreturn=i;
      break;
    }
  }
  return lreturn;
}
//Utility
function AreTheVertexEqual(vetex1,vetex2){
  var lreturn=false;
  if ( IcAreDoublesEqual(vetex1.Point.X, vetex2.Point.X)
        && IcAreDoublesEqual(vetex1.Point.Y, vetex2.Point.Y)
        && IcAreDoublesEqual(vetex1.Point.Z, vetex2.Point.Z)) {
    lreturn = true;
  }
  return lreturn;
}
//Is single zone
function IsSingleZoneTopo(){
  var lreturn=false;
  protoGroup = ICGetProtoGroup();
  if(protoGroup == null)
    return lreturn;
  childList = protoGroup.Children;
  for (var i = 1; i <= childList.Count; i++) {
    child = childList.Item(i);
    if (ds.Script.id_BodyGroup != child.Class) continue;

    protoList = child.Prototypes;
    if (!protoList || !protoList.count)
      continue;

    var pistonType3 = 0;
    var pistonBody = -1, partId = 0;
    str1 = String(child.Name);
    if (str1.indexOf("Single-Zone") != -1){
      lreturn=true;
    }
  }
  if(!lreturn)
  {
    var topoArr=new Array();
    var partArr=new Array();
    var PortNsList = ICGetNSSupports("","-port",topoArr,partArr);
    var vlayerNsList = ICGetNSSupports("","-vlayer",topoArr,partArr);
    if((PortNsList.length > 0) && (vlayerNsList.length == 0))
      lreturn=true;
  }
  return lreturn;
}
function IcSuppressPinch(){
  var branch = ds.Tree.FirstActiveBranch;
  var meshGroup = branch.MeshControlGroup;
  var mehctrls = meshGroup.MeshControls;
  var meshctrl;
  //We need to suppress the Pinch controls whose supports are lost in regeneration
  for (j = 1; j <= mehctrls.Count; j++) {
    meshctrl = mehctrls.item(j);
    if (meshctrl.ControlType != ds.Script.id_Merge) //suppress only Pinch controls
      continue;
    if (ds.Script.id_FullyDefined != meshctrl.State) {
      if (meshctrl.SubValue)
        meshctrl.SubValue = false;
    }
  }
}
function ICDefineValveSeatFaceSizing(){
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var Assys, Assy;

  if (!ds.Tree.FirstActiveBranch) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  var nsTopoArr=new Array(),nsPartArr=new Array();
  var valveLifts = getValveLifts();
  for (var j = 0; j < valveLifts.length/2; j++) {
    sm.Clear();
    ICGetNSSupports(valveLifts[2*j],"-seat",nsTopoArr,nsPartArr);
    ICGetNSSupports("interior-",valveLifts[2*j],nsTopoArr,nsPartArr);
    if (!sm.SelectedCount)
       continue;
    var mehctrls = meshGroup.MeshControls;
    var MeshCtrlObj = null;
    var ctrlName=" ("+valveLifts[2*j]+"-seat)";
    for (i = 1; i <= mehctrls.Count; i++) {
      meshctrl = mehctrls.item(i);
      var str1 = new String(meshctrl.Name);
      if ((str1.indexOf(ctrlName) != -1)) {
        if (meshctrl.ControlType == ds.Script.id_Size) {
          MeshCtrlObj = meshctrl;
          break;
        }
      }
    }
    //Body sizing
    if(!MeshCtrlObj){
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      MeshCtrlObj.LocalAdvancedSizeFunction=1; //Curvature
      MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
      MeshCtrlObj.Name = MeshCtrlObj.Name + ctrlName;
      ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
    }
    if (MeshCtrlObj) {
      var lift = 0.2;
      if (valveLifts[2*j+1] > 0)
        lift = valveLifts[2*j+1];
      var seatSize = lift/3.3; //Ensure three elements between seat and valve
      if(seatSize > meshGroup.MinSizeSF)
        seatSize = meshGroup.MinSizeSF;
      MeshCtrlObj.ESize = seatSize;
      MeshCtrlObj.SizingType = 1; //Hard
    }
  }

}
function ICDefineSingleZoneInflation(IsRegen){
  var meshGroup, MeshCtrlObj, MeshCtrlGrpNode;
  var Assys, Assy;

  if (!ds.Tree.FirstActiveBranch) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);
  
  var nsTopoArr=new Array(),nsPartArr=new Array();
  sm.Clear();
  ICGetNSSupports("fluid","-port",nsTopoArr,nsPartArr);
  //ICGetNSSupports("fluid","-layer-cylinder",nsTopoArr,nsPartArr);
  ICGetNSSupports("fluid","-piston",nsTopoArr,nsPartArr);
  ICGetNSSupports("fluid","-ch",nsTopoArr,nsPartArr);
  var mehctrls = meshGroup.MeshControls;
  var MeshCtrlObj = null;
  for (i = 1; i <= mehctrls.Count; i++) {
    meshctrl = mehctrls.item(i);
    var str1 = new String(meshctrl.Name);
    if ((str1.indexOf("(all-faces)") != -1)) {
      if (meshctrl.ControlType == ds.Script.id_Inflation) {
        MeshCtrlObj = meshctrl;
        break;
      }
    }
  }
  if (!MeshCtrlObj) {
    MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Inflation);
    MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
    MeshCtrlObj.Name = MeshCtrlObj.Name + " (all-faces)"
    ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
  }
  if(!IsRegen)
  {
    if(ChInflation==0)
      MeshCtrlObj.SubValue=false;
    else
      MeshCtrlObj.SubValue=true;
  }
  sm.Clear();
 //cyl-head cyl-piston cyl-tri exvalve1-ch exvalve-1-port exvalve1-seat exvalve1-stem invalve1-ch invalve1-ib invalve-1-port invalve1-seat invalve1-stem piston
  ICGetNSSupports("cyl-tri","",nsTopoArr,nsPartArr);
  ICGetNSSupports("cyl-head","",nsTopoArr,nsPartArr);
  ICGetNSSupports("cyl-piston","",nsTopoArr,nsPartArr);
  ICGetNSSupports("exvalve","",nsTopoArr,nsPartArr);
  ICGetNSSupports("invalve","",nsTopoArr,nsPartArr);
  //ICGetNSSupports("piston","",nsTopoArr,nsPartArr);
  MeshCtrlObj.SourceGeometry = sm;
}
function ICEngineSetSolverParameters(solver,surfaceMeshPath)
{
  ICSetSessionVaribale("ICESolver", solver);
  ICSetSessionVaribale("ICEForteMeshFilePath", surfaceMeshPath);
}
function ICEngineSetupAndGenerateMesh(setupInput)
{
  ICEAddToolBar();
  var solver = ICGetSessionVaribale("ICESolver");
  var previousValue = ICGetSessionVaribale("ICEnginePanelMeshCell");
  if(solver=="")
    solver="Fluent";
  if(solver=="Fluent")
  {
    ICEngineResetSolverType();
    ICEngineSetupMesh(setupInput,"True");
    var lIssueFound=checkForNSTransferError();
    if(!lIssueFound)
      IcGenerateMesh();
  }
  else
  {
    ICEngineResetSolverType();
    ICEngineSetupMesh(setupInput,"True");
    //Generate the mesh and export it
    IcGenerateMesh();
    var protoGroup = ICGetProtoGroup();
    if (!protoGroup)
      return;
    childList = protoGroup.Children;
    if(childList.Count!=1)
      return;
    var proto = childList.item(1);
    childList = proto.Children;
    var surfaceMeshCreated=false;
    var surfaceMeshPath = ICGetSessionVaribale("ICEForteMeshFilePath");
    if(surfaceMeshPath!="")
    {
      var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject"); 
      if (fileSys.FileExists(surfaceMeshPath)) 
        surfaceMeshCreated=true;
    }
    
    if(0/*surfaceMeshCreated && (childList.Count == 2)*/)
    {
      var PortProto;
      proto = childList.item(1);
      var name = new String(proto.Name);
      if(name.indexOf("forte-sphere") == -1)
      {
        PortProto=proto;
        proto = childList.item(2);
      }
      else
      {
        PortProto=childList.item(2);
      }
      if(PortProto.MeshVolume>0)//PortProto.State == ds.Script.id_Meshed
      {
        if(PortProto.Suppressed)
          PortProto.Suppressed = false;
        proto.Suppressed = true;
      }
      else
      {
        PortProto.Suppressed = true;
        proto.Suppressed = false;
      }
    }
  }
  
}
function ExportMSHFile(filepath)
{
   IcActivateBranch();
   if(typeof (ds.Tree.FirstActiveBranch) == "undefined")
     return;
   
   var meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
    if(meshGroup)
    {
      try
      {
        meshGroup.WriteFluentInputFile(filepath);
      }
      catch(error)
      {
      }
    }
}
function ICEForteAMGSetup() {
  if (typeof (ds.Script.lv) != "undefined")
    ds.Script.lvFroceOutOfEdit();
  
  ICSetSessionVaribale("ICEForteSetupDone","true")

  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;
  var partCount = 0;
  if (branch.Prototypes)
    partCount = branch.Prototypes.Count;
  if (partCount == 0)                   // if no geometry return
    return;

  //Set the units to mm
  //ds.Script.doUnitsMenu(2);
  ds.UnitSystemID = 2;

  // Finding the mesh size
  //=============================
  //var meshSize = getMeshSize();

  // Meshing Options
  //=============================
  meshGroup.PhysicsPreference = 2;
  meshGroup.SolverPreference = 0;
  meshGroup.AdvancedSizeFunction = 2;
  meshGroup.MaxFaceElementSize = MaxMeshSize;
  meshGroup.MaxSizeSF = MaxMeshSize ;
  meshGroup.MinSizeSF = MinMeshSize;
  meshGroup.MeshDefeatureTol = MinMeshSize/2.0;  
  var protoGroup = ICGetProtoGroup();
  if (!protoGroup)
    return;
  childList = protoGroup.Children;
  if(childList.Count!=1)
    return;
  var proto = childList.item(1);
  childList = proto.Children;
  for (i = 1; i <= childList.Count; i++) {
    proto = childList.item(i);
    var name = new String(proto.Name);
    if(name.indexOf("forte-sphere") != -1)
      proto.Suppressed = true;
    else
      proto.Suppressed = false;
  }
}
function ICEngineSetupMesh(setupInput,setupOnEdit,sprakSOI)
{
//debugger;
  //In case of batch mode, first active branch is returned as null, to avoid it call this function.
  ICEAddToolBar();
  IcActivateBranch();
  var solver = ICGetSessionVaribale("ICESolver");
  if(setupInput == ""){
    setupInput=ICEGetPanelSettings();
    var setupPanel = ICGetSessionVaribale("ICEnginePanel");
    //For previous version files, we dont want modify the mesh controls if they open it.
    if(setupPanel!=""){
      IcRegenerateNew(); 
      return;
    }
  }
  if(solver!="Forte")  
    IcRegenerateNew(); 
  if(!sprakSOI)//If undefined, set it to ""
    sprakSOI="";
  var previousValue = ICGetSessionVaribale("ICEnginePanelMeshCell");
  var sparkSessionVal = ICGetSessionVaribale("ICEnginePanelSparkSOI");
  if(sprakSOI=="")//If this method is not called from key grid, then SparkSOI will be "", then we should not check it.
    sprakSOI = sparkSessionVal;
  var changeSparkOnly=false;
  
  if(ICAreStringsSameAfterTokenizing(setupInput,previousValue,";") && (sparkSessionVal == sprakSOI))
  {
   return;
  }
  else if(setupInput == previousValue)
    changeSparkOnly = true;
  ICSetSessionVaribale("ICEnginePanelMeshCell", setupInput);
  ICSetSessionVaribale("ICEnginePanelSparkSOI", sprakSOI);
  var allInputs = setupInput+";"+sprakSOI;
  var lMeshType="",lVT="",lRefSize=0,lNbInflation="",lSparkSOI="",lSoiRadius="",lChInflation="";
  var colunSplit = allInputs.split(";");
  for(var i=0; i<colunSplit.length; ++i)
  {
    if(colunSplit[i] == "") 
      continue;
    var dashSplit = colunSplit[i].split("-");
    if (dashSplit.Length < 2) 
      continue;
    switch (dashSplit[0])
    {
      case "MeshType":
        lMeshType = dashSplit[1];
        break;
      case "RefSize":
        lRefSize = dashSplit[1];
        break;
      case "VT":
        lVT = dashSplit[1];
        break;
      case "NbInflation":
        lNbInflation = dashSplit[1];
        break;
      case "SparkSOI":
        lSparkSOI = dashSplit[1];
        break;
      case "SoiRadius":
        lSoiRadius = dashSplit[1];
        break;
      case "ChInflation":
        lChInflation = dashSplit[1];
        break;
    }
  }
  if(lVT=="Low")
    lVT = "0";
  else if(lVT=="Medium")
    lVT="1";
  else if(lVT=="None")
    lVT="3";
  else //Default: High
    lVT="2";
  if(solver=="Forte"){
    if(lMeshType=="Coarse")
      lMeshType = "0";
    else if(lMeshType=="Fine")
      lMeshType="2";
    else //Default: Medium
      lMeshType="1";    
    ICESetForteSettings(setupOnEdit,lMeshType,lRefSize) ;
    return;
  }
  else if (IsPortFlow()) {
    if(lMeshType=="CutCell")
      lMeshType = "1";
    else //Default: Hybrid
      lMeshType="0";
    ICESetPortFlowSettings(setupOnEdit,lMeshType,lRefSize,lVT,lNbInflation);
  }
  else if(IsCombustion()){
    if(lMeshType=="Fine")
      lMeshType="1";
    else //Default: Coarse
      lMeshType = "0";
    ICESetCombustionSettings(setupOnEdit,lMeshType,lRefSize,lVT,lNbInflation);
  }
  else{
    if(lMeshType=="Coarse")
      lMeshType = "0";
    else if(lMeshType=="Fine")
      lMeshType="2";
    else //Default: Medium
      lMeshType="1";
    ICESetColdFlowSettings(setupOnEdit,lMeshType,lRefSize,lVT,lNbInflation,lSparkSOI,lSoiRadius,changeSparkOnly,lChInflation);
  }
}
function ICEGetPanelSettings()
{
  var lMeshType = ICGetPanelField("MeshType");
  if (IsPortFlow())
  {
    if(lMeshType == "1")
      lMeshType="CutCell";
    else
      lMeshType="Hybrid";
  }
  else if(IsCombustion())
  {
    if(lMeshType=="1")
      lMeshType="Fine";
    else
      lMeshType = "Coarse";
  }
  else
  {
    if(lMeshType=="0")
      lMeshType = "Coarse";
    else if(lMeshType=="2")
      lMeshType="Fine";
    else //Default: Medium
      lMeshType="Medium"; 
  }
  var lVT = ICGetPanelField("VT");
  if(lVT=="0")
    lVT = "Low";
  else if(lVT=="1")
    lVT="Medium";
  else if(lVT=="3")
    lVT="None";
  else //Default: High
    lVT="High";
  var lRefSize = ICGetPanelField("RefSize");
  if(lRefSize=="")//Default
  {
    lRefSize = round(getMeshSize());
  }
  var lNbInflation = ICGetPanelField("NbInflation")
  if(lNbInflation=="")//Default
  {
    if (IsPortFlow())
      lNbInflation="8";
    else
     lNbInflation="3";
  }
  var lChInflation = ICGetPanelField("ChInflation")
  if(lChInflation=="")//Default
  {
     lChInflation="0";
  }
  
  return "MeshType-"+lMeshType+";VT-"+lVT+";NbInflation-"+lNbInflation+";RefSize-"+lRefSize+";ChInflation-"+lChInflation;
}
function ICEWritePanelDefaults(path) {
  var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
  var textStream = fileSys.CreateTextFile(path, true);
  var defaultVal = ICEGetPanelSettings();
	textStream.WriteLine(defaultVal);
  textStream.Close();
}
//Need to do the same changes in panel html file as well, both need to be in sync.
function ICESetForteSettings(setupOnEdit,inpMeshType,lRefSize) 
{
  //Convert old versions panel string
  ICConvertPanelStringFormat();
  MeshType = inpMeshType;
  RefSize = getMeshSize();
  RefSize = round(RefSize);
  var creviceMeshSize =  getCreviceMeshSize();
  if (MeshType == "0") {
    RefSize = round(RefSize * 1.5);
  }
  else if (MeshType == "1") {
  }
  else {
    RefSize = round(RefSize * 0.80);
  }
  if(lRefSize>0)
    RefSize = new Number(lRefSize);

  MinMeshSize = round((RefSize / 4.0));
  MaxMeshSize = round((RefSize * 3.0));
  value = ICGetPanelField("RefSize");
  if( (value != "") && (RefSize == value))
  {
    value = ICGetPanelField("MinMeshSize");
    if(value!="")
      MinMeshSize=new Number(value);
    value = ICGetPanelField("MaxMeshSize");
    if(value!="")
      MaxMeshSize=new Number(value);
  }

  //Highest priority to inputs
  var previousSettings = ICGetSessionVaribale("ICEnginePanel");
  ICSetPanelSessionVarFromGlobalVars();
  var newSettings = ICGetSessionVaribale("ICEnginePanel");
  if(setupOnEdit == "False")
    return;
  if(!ICAreStringsSameAfterTokenizing(newSettings,previousSettings,";") || IsNew())
    ICEForteAMGSetup();
}
//Default values are also set in ICEGetPanelSettings function. Please change there as well.
function ICESetPortFlowSettings(setupOnEdit,inpMeshType,lRefSize,inpVtType,inpNbInfation) {
  //Convert old versions panel string
  ICConvertPanelStringFormat();
  
  MeshType = inpMeshType;
  RefSize = getMeshSize();
  RefSize = round(RefSize);
  var valveLifts = getValveLifts();
  var minLift = 0.;
  for (var i = 0; i < (valveLifts.length)/2; ++i) {
    if (i == 0)
      minLift = valveLifts[2 * i + 1];
    else if(minLift > valveLifts[2 * i + 1])
      minLift = valveLifts[2 * i + 1];
  }
  if (MeshType == "0") {
    NormalAngle = "30";
    GrowthRate = "1.2";
    ChGrowthRate = "1.15";
    ProxNumCells = "3";
  }
  else {
    NormalAngle = "18";
    GrowthRate = "1.05";
    ChGrowthRate = "1.05";
    ProxNumCells = "5";        
  }
  var meshTypeChanged=true;
  value = ICGetPanelField("MeshType")
  if((value!="")&&(value == MeshType))
  {
    meshTypeChanged=false;
    value = ICGetPanelField("NormalAngle");
    if(value!="")
      NormalAngle=new Number(value);
    value = ICGetPanelField("GrowthRate");
    if(value!="")
      GrowthRate=new Number(value);
    value = ICGetPanelField("ChGrowthRate");
    if(value!="")
      ChGrowthRate=new Number(value);
    value = ICGetPanelField("ProxNumCells");
    if(value!="")
      ProxNumCells=new Number(value);
  }
  Pinch = "0.1";
  value = ICGetPanelField("Pinch");
  if(value!="")
    Pinch=new Number(value);
  NbInflation = "8";
  value = ICGetPanelField("NbInflation");
  if(value!="")
    NbInflation=new Number(value);
  
  if(lRefSize>0)
    RefSize = new Number(lRefSize);
  if(inpNbInfation!="")
    NbInflation=inpNbInfation;

  if (MeshType == "0") {
    MinMeshSize = round(RefSize/2.);
    ProxMinMeshSize = round((RefSize / 3.0));
    MaxMeshSize = round((RefSize * 5.0));
  }
  else {
    MinMeshSize = round((RefSize / 3.0));
    ProxMinMeshSize = round((RefSize / 3.0));
    MaxMeshSize = round((RefSize * 16.0/3.0));
  }
  ChSize = round((1.5 * RefSize));
  var lift = minLift;
  lift = lift / 8;
  if (lift < RefSize / 8.0)
    lift = RefSize / 8.0;
  else if (lift > RefSize)
    lift = RefSize;
  ProxValveSize = round(lift);

  value = ICGetPanelField("RefSize")
  if(!meshTypeChanged&&(value!="")&&(value == RefSize))
  {
    value = ICGetPanelField("MinMeshSize");
    if(value!="")
      MinMeshSize=new Number(value);
    value = ICGetPanelField("ProxMinMeshSize");
    if(value!="")
      ProxMinMeshSize=new Number(value);
    value = ICGetPanelField("MaxMeshSize");
    if(value!="")
      MaxMeshSize=new Number(value);
    value = ICGetPanelField("ChSize");
    if(value!="")
      ChSize=new Number(value);
    value = ICGetPanelField("ProxValveSize");
    if(value!="")
      ProxValveSize=new Number(value);
  }

  var previousSettings = ICGetSessionVaribale("ICEnginePanel");
  ICSetPanelSessionVarFromGlobalVars();
  var newSettings = ICGetSessionVaribale("ICEnginePanel");
  if(setupOnEdit == "False")
    return;
  if(!ICAreStringsSameAfterTokenizing(newSettings,previousSettings,";") || IsNew())
    DefinePortFlowMesh();
}
function ICESetCombustionSettings(setupOnEdit,inpMeshType,lRefSize,inpVtType,inpNbInfation) {
  //Convert old versions panel string
  ICConvertPanelStringFormat();

  RefSize = getMeshSize();
  RefSize = round(RefSize);
  ChamberBottomMeshSize = getChmaberBottomMeshSize();
  ChamberBottomMeshSize = round(ChamberBottomMeshSize);

  if (inpMeshType == "0") {
    NbInflation = 3;
  }
  else {
    RefSize = round(RefSize * 2. / 3.);
    NbInflation = 5;
  }
  if(lRefSize>0)
    RefSize = new Number(lRefSize);
  IsInflationOn = "0";
  if(inpNbInfation!="")
  {
    NbInflation=inpNbInfation;
    if(NbInflation == "0")
      IsInflationOn = "1";
  }

  MinMeshSize = round(RefSize/5.);
  MaxMeshSize = round(RefSize /2.);
  value = ICGetPanelField("RefSize")
  if((value!="")&&(value == RefSize))
  {
    value = ICGetPanelField("MinMeshSize");
    if(value!="")
      MinMeshSize=new Number(value);
    value = ICGetPanelField("MaxMeshSize");
    if(value!="")
      MaxMeshSize=new Number(value);
    value = ICGetPanelField("IsInflationOn");
    if(value!="")
      IsInflationOn=new Number(value);
  }
    
  MeshType = inpMeshType;
  var previousSettings = ICGetSessionVaribale("ICEnginePanel");
  ICSetPanelSessionVarFromGlobalVars();
  var newSettings = ICGetSessionVaribale("ICEnginePanel");
  if(setupOnEdit == "False")
    return;
  if(!ICAreStringsSameAfterTokenizing(newSettings,previousSettings,";") || IsNew())
    DefineSectorCombMesh();
}
//Need to do the same changes in panel html file as well, both need to be in sync.
function ICESetColdFlowSettings(setupOnEdit,inpMeshType,lRefSize,inpVtType,inpNbInfation,inpsparkSOI,inpSparkRad,inpChangeSparkOnly,lChInflation) 
{
  //Convert old versions panel string
  ICConvertPanelStringFormat();
  MeshType = inpMeshType;
  VT= inpVtType;
  RefSize = getMeshSize();
  RefSize = round(RefSize);
  var creviceMeshSize =  getCreviceMeshSize();
  if (MeshType == "0") {
    RefSize = round(RefSize * 1.5);
    NormalAngle = "30";
    GrowthRate = "1.2";
    NbInflation = "3";
    ChGrowthRate = "1.2";
    IntfCrevicePiston = round(creviceMeshSize);
    CreviceNoOfLayers = "2";
  }
  else if (MeshType == "1") {
    NormalAngle = "30";
    GrowthRate = "1.2";
    NbInflation = "3";
    ChGrowthRate = "1.15";
    IntfCrevicePiston = round(2 * creviceMeshSize/3);
    CreviceNoOfLayers = "3";
  }
  else {
    RefSize = round(RefSize * 0.80);
    refMeshSize = RefSize; 
    NormalAngle = "18";
    GrowthRate = "1.2";
    NbInflation = "5";
    ChGrowthRate = "1.15";
    IntfCrevicePiston = round(creviceMeshSize/3);
    CreviceNoOfLayers = "4";
  }
  if(lRefSize>0)
    RefSize = new Number(lRefSize);
  Pinch = "0.1";
  var value = ICGetPanelField("Pinch");
  if(value!="")
    Pinch=new Number(value);
  ChInflation="0";
  value = ICGetPanelField("ChInflation");
  if(value!="")
    ChInflation=new Number(value);
  if(lChInflation!="")
    ChInflation = lChInflation;
  value = ICGetPanelField("MeshType")
  if((value!="")&&(value == MeshType))
  {
    value = ICGetPanelField("NormalAngle");
    if(value!="")
      NormalAngle=new Number(value);
    value = ICGetPanelField("GrowthRate");
    if(value!="")
      GrowthRate=new Number(value);
    value = ICGetPanelField("ChGrowthRate");
    if(value!="")
      ChGrowthRate=new Number(value);
    value = ICGetPanelField("IntfCrevicePiston");
    if(value!="")
      IntfCrevicePiston=new Number(value);
    value = ICGetPanelField("CreviceNoOfLayers");
    if(value!="")
      CreviceNoOfLayers=new Number(value);
  }

  MinMeshSize = round((RefSize / 3.0));
  MaxMeshSize = round((RefSize * 3.0));
  VlayerSize = round((RefSize / 2.0 ));
  IbSize = round((RefSize / 2.0));
  IntfVlayerCh = round((RefSize / 2.0));
  if(IsSingleZoneTopo())
    ChSize = round(RefSize*1.5);
  else if(IsStraightValveEngine() || (DoesItContainPorts()==0))
    ChSize = round(RefSize*1.0);
  else
    ChSize = round((RefSize*1.5));
  SoiRadius = round((RefSize * 3.3));
  value = ICGetPanelField("RefSize");
  if( (value != "") && (RefSize == value))
  {
    value = ICGetPanelField("MinMeshSize");
    if(value!="")
      MinMeshSize=new Number(value);
    value = ICGetPanelField("MaxMeshSize");
    if(value!="")
      MaxMeshSize=new Number(value);
    value = ICGetPanelField("VlayerSize");
    if(value!="")
      VlayerSize=new Number(value);
    value = ICGetPanelField("IbSize");
    if(value!="")
      IbSize=new Number(value);
    value = ICGetPanelField("IntfVlayerCh");
    if(value!="")
      IntfVlayerCh=new Number(value);
    value = ICGetPanelField("ChSize");
    if(value!="")
      ChSize=new Number(value);
    value = ICGetPanelField("SoiRadius");
    if(value!="")
      SoiRadius=new Number(value);
    value = ICGetPanelField("ChSize");
    if(value!="")
      ChSize=new Number(value);
  }

  //Highest priority to inputs
  if(inpSparkRad != "")
    SoiRadius = inpSparkRad;
  if(inpNbInfation!="")
    NbInflation=inpNbInfation;
  if(inpsparkSOI != "")
    SparkSOI = inpsparkSOI;
  else if ((isSparkCenterAttrDefined()>0) && (checkSparkActivateAngles() > 0))
    SparkSOI = 1;
  else 
    SparkSOI = 0;
    
  if(inpChangeSparkOnly)
  {
   ICEDefineSparkBOIMesh(0);
   ICSetPanelSessionVarFromGlobalVars();
   return;
  }
  var previousSettings = ICGetSessionVaribale("ICEnginePanel");
  ICSetPanelSessionVarFromGlobalVars();
  var newSettings = ICGetSessionVaribale("ICEnginePanel");
  if(setupOnEdit == "False")
    return;
  if(!ICAreStringsSameAfterTokenizing(newSettings,previousSettings,";") || IsNew())
    IcSetMeshSettings();
}
function round(nb){
  var meshSize = nb*1000;
  meshSize = Math.ceil(meshSize);
  meshSize = meshSize/1000;
  return meshSize;
}
function IcRegenerateNew() {
  var GeometryModified = ICGetSessionVaribale("GeometryModified");
  ICDeleteSessionVaribale("GeometryModified");
  if (!ds.Tree.FirstActiveBranch) return;
  if (!ds.Tree.FirstActiveBranch.MeshControlGroup) return;
  var meshCtrls = ds.Tree.FirstActiveBranch.MeshControlGroup.MeshControls;
  if(!meshCtrls || meshCtrls.Count == 0)
  {
    return;
  }
  if (IsPortFlow()) {
    var strprev = ICGetSessionVaribale("ICEngineValveLiftPlaneOff");
    var strcurr = GetPortFlowSessionVariableString();
    if ((GeometryModified=="GeometryModified")||(IsAllNSImported() && (strprev != strcurr) && (strprev != ""))) {
      ICRegenratePortFlow();
      ICSetSessionVaribale("ICEngineValveLiftPlaneOff", strcurr);
      ICECheckNSAfterRegen();
    }
  }
  else if (IsCombustion()) {
    if ((GeometryModified=="GeometryModified")||(IsAllNSImportedSector())) {
      ICRegenrateSector();
      ICECheckNSAfterRegen();
    }
  }
  else
  {
    var nbDuplicates = getNbDuplicateNS();
    if ((GeometryModified=="GeometryModified")||(nbDuplicates > 0)){
      ICDeleteDuplicateNS();
      ICRegenrateColdFlow();
      ICECheckNSAfterRegen();
    }
  }
  CreateSectionPlanes();
  CreateViews();
}
function IcActivateBranch()
{
  if(!ds.Tree.FirstActiveBranch || !ds.Tree.FirstActiveBranch.Model)
  {
    if (ds.Tree.Branches.Count)
    {
      branch = ds.Tree.Branches.Item(1);
      if(branch){
	    ds.Tree.ClearActiveObjects();
        ds.Tree.AddActiveObject(branch.Model);
      }
    }
  }
}
function ICEAddSparkCoordinateSystems () {
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  //var attrs = Assy.AttributesByName(1,"ICEngine_ValveLifts");
  var sparks;
  sparks = getSparkCenters();
  for (var i = 0; i < sparks.length; i++) {
    sparkCoord = sparks[i].split(",");
    //check the size
    if (sparkCoord.length < 3) 
      continue;
    sparkCoordX = sparkCoord[0];
    sparkCoordY = sparkCoord[1];
    sparkCoordZ = sparkCoord[2];
    var branch = ds.Tree.FirstActiveBranch;
    var CoorSystemCtrlGrpNode;
    var coordSysGrp = branch.CoordinateSystemGroup;
    var coorSystemControls = coordSysGrp.CoordinateSystems;
    var coordSystemObj  = null; 
    var coorSystemControl;
    sm.Clear();
    for (var j = 1; j <= coorSystemControls.Count; j++) {
    coorSystemControl = coorSystemControls.item(j);
    var str = new String(coorSystemControl.Name);
    if (str.indexOf("ice_spark_center_" + i) == -1) continue;
    coordSystemObj = coorSystemControl;
  }
    if (!coordSystemObj) {
      coordSystemObj = coordSysGrp.AddCoordinateSystem(sm);
      if (coordSystemObj) {
        coordSystemObj.OriginXLocation = sparkCoordX;
        coordSystemObj.OriginYLocation = sparkCoordY;
        coordSystemObj.OriginZLocation = sparkCoordZ;
        coordSystemObj.OriginAlignment = 0; //defined by Global Coordinates
        coordSystemObj.PrimaryAxis = 1;
        coordSystemObj.PrimaryAxisAlignment = 0;
        coordSystemObj.SecondaryAxis = 1;
        coordSystemObj.SecondaryAxisAlignment = 0;
        coordSystemObj.Name = "ice_spark_center_" + i;
        CoorSystemCtrlGrpNode = ds.Script.GetNode(coordSysGrp.ID);
        ds.Script.addNodeAndChildren(coordSystemObj, CoorSystemCtrlGrpNode);
      }
    }
  }
}
function getSparkCenters(){
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  var attrs = Assy.AttributesByName(1,"ICEngine_Spark_Center");
  var CA = 0.;
  var coord = new Array();
  for (var i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.String);
    if(str != "")
      coord = str.split(";");
  }
  return coord;
}
function ICEDefineSparkBOIMesh(IsRegen) {
  var i, j, str, id;
  var branch = ds.Tree.FirstActiveBranch;
  var coordSysGrp = branch.CoordinateSystemGroup;
  var coorSystemControls = coordSysGrp.CoordinateSystems;
  var nsl, ns;
  var meshGroup, MeshCtrlGrpNode;
  var meshSize = getPanelRefSize();
  var Assys, Assy;
  var partid, topid, pos;
  var arr;

  if (!ds.Tree.FirstActiveBranch) 
    return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) 
    return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) 
    return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) 
    return;
  Assy = Assys.Item(1);

  arr = new Array();
  //Sizing for spark center,  body of influence BOI
  sm.Clear();
  var topoArr = new Array();
  var partArr = new Array();
  ICGetNSSupports("fluid-ch","",topoArr,partArr);
  if (sm.SelectedCount==0)
    return;
  for (var i = 1; i <= coorSystemControls.Count; i++) {
    str = new String(coorSystemControls.Item(i).Name);
    if (str.indexOf("ice_spark_center_") == -1) continue;
    var mehctrls = meshGroup.MeshControls;
    var meshctrl;
    var MeshCtrlObj=null;
    for (var j = 1; j <= mehctrls.Count; j++) {
      meshctrl = mehctrls.item(j);
      if (meshctrl.ControlType != ds.Script.id_Size)
        continue;
      var str1 = new String(meshctrl.Name);
      if (str1.indexOf(str) == -1) 
        continue;
      MeshCtrlObj = meshctrl;
    }
    //Body sizing BOI
    if (!MeshCtrlObj) {
      MeshCtrlObj = meshGroup.AddMeshControl(sm, ds.Script.id_Size); // 26 is for SizeControl
      if (MeshCtrlObj) {
        id = coorSystemControls.Item(i).Id;
        MeshCtrlObj.SubType= 2; //BOI
        MeshCtrlObj.ESize = meshSize / 5; //*meshSize*/; // specify your size specifycation
        if (!IsRegen){
          MeshCtrlObj.InnerRadius= SoiRadius //meshSize*3.3;
        }
        MeshCtrlObj.SphereCenter= id;
        MeshCtrlObj.SizingTransition = ChGrowthRate;
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObj.Name = MeshCtrlObj.Name + "(" + str + ")";
        ds.Script.addNodeAndChildren(MeshCtrlObj, MeshCtrlGrpNode);
        if (SparkSOI==0)
          MeshCtrlObj.SubValue = false;
      }
    }
    else {
        var str1 = MeshCtrlObj.Name;
        MeshCtrlObj.GeometrySelection = sm;
        if (!IsRegen){
          MeshCtrlObj.InnerRadius= SoiRadius;
        }
        MeshCtrlObj.Name = str1; //Name is getting lost after setting supports.
        if (SparkSOI==0) 
          MeshCtrlObj.SubValue = false;
        else
          MeshCtrlObj.SubValue = true;
    }
  }
}
function isSparkCenterAttrDefined(){
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  breturn = -1;
  var attrs = Assy.AttributesByName(1,"ICEngine_Spark_Center");
  var CA = 0.;
  var coord = new Array();
  for (var i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.String);
    if(str != "")
      coord = str.split(";");
  }
  if(coord.length > 0)
    breturn=1;
  return breturn;
}
function checkSparkActivateAngles(){
  var Assys = pm.assemblies;
  var Assy = Assys.Item(1);
  breturn = -1;
  var attrs = Assy.AttributesByName(1,"ICEngine_Spark_Default");
  var CA = 0.;
  var coord = new Array();
  for (var i = 1; i <= attrs.Count; ++i) {
    attr = attrs.item(i);
    var str = new String(attr.Integer);
    if(str == "1")
      breturn = 1;
  }
  return breturn;
}
//Utility
function ICGetMeshControlByName(contains,controlType){
  var MeshCtrlFound = null;
  var meshGroup=null;
  if (ds.Tree.FirstActiveBranch)
    meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (meshGroup)
  {
    var mehctrls = meshGroup.MeshControls;
    for (i = 1; i <= mehctrls.Count; i++) {
      meshctrl = mehctrls.item(i);
      var str1 = new String(meshctrl.Name);
      if ((str1.indexOf(contains) != -1)) {
        if (meshctrl.ControlType == controlType) {
          MeshCtrlFound = meshctrl;
          break;
        }
      }
    }
  }
  return MeshCtrlFound;
}
//Utility
function ICGetProtoGroup()
{
  var protoGroup = null;
  if(!ds.Tree.FirstActiveModel)
    IcActivateBranch();
  if(ds.Tree.FirstActiveModel)
    protoGroup = ds.Tree.FirstActiveModel.PrototypeGroup;
  return protoGroup;
}
function ICEDoAutoPinch()
{
	sm.Clear();
    try
    {
        // create the progress pane
        var progressObj = ds.Script.CreateActiveXObject(ds.Script.GenWBProgId("AnsCoreObjects.AnsProgress"));
		
        var branch = ds.Tree.FirstActiveBranch;
	    if( branch )
	    {
		    var meshGroup = branch.MeshControlGroup;
		    if( meshGroup )
		        meshGroup.AutoPinch(progressObj);
        }
    }
    catch(error)
    {
	    return 0;
    }
}
function ICEngineSetNSCheckPaths(DMNSFile,NSErrorFile)
{
  ICSetSessionVaribale("DMNSFile", DMNSFile);
  ICSetSessionVaribale("NSErrorFile", NSErrorFile);
}
function ICECheckNSAfterRegen()
{
  var lIssueFound=false;
  var nsl, ns;
  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  var nsArr=new Array();
  for (var j = 1; j <= nsl.Count; ++j) {
    ns = nsl.item(j);
    nsArr.push(new String(ns.Name));
  }
  var DMNSFile = ICGetSessionVaribale("DMNSFile");
  var NSErrorFile = ICGetSessionVaribale("NSErrorFile");

  var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
  if(fileSys.FileExists(NSErrorFile))
    fileSys.DeleteFile(NSErrorFile);
  if(fileSys.FileExists(DMNSFile)) {
    var f = fileSys.GetFile(DMNSFile);
    var ForReading = 1;
    var TristateUseDefault = 0;//unicode
    var ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
    var str = ts.ReadLine();
    var notFound = new Array();
    while(str != ""){
      if (ts.AtEndOfStream)
        break;
      str = ts.ReadLine();
      var pos = FindInArray(nsArr,str);
      if(pos==-1)
        notFound.push(str);
    }
    ts.Close();
    if(notFound.length > 0){
      ICSetSessionVaribale("NSTransferErrorDetected","x");
      lIssueFound = true;
      var textStream = fileSys.CreateTextFile(NSErrorFile, true);
      for(var i=0; i<notFound.length; ++i)
        textStream.WriteLine(notFound[i]);
      textStream.Close();
    }
    else
      ICDeleteSessionVaribale("NSTransferErrorDetected");
  }
}
function checkForNSTransferError()
{
  var IssueFound=false;
  //delete ErrorFile if Mesh is Reset
  if(ICGetSessionVaribale("NSTransferErrorDetected") == "")
  {
    var NSErrorFile = ICGetSessionVaribale("NSErrorFile");
    var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
    if(fileSys.FileExists(NSErrorFile))
      fileSys.DeleteFile(NSErrorFile);
  }
  else
    IssueFound = true;
  return IssueFound;
}
function ICEDefineChamberInflation(IsRegen) {
  var i, j, k, l, str1;
  var nsl, ns;
  var Assys, Assy;
  var ns, name, found;
  var partid, topid, pos;
  var faces, Part, body, face;
  var arr, arrch;

  if (!ds.Tree.FirstActiveBranch) return;
  nsl = ds.Tree.FirstActiveBranch.Components;
  if (!nsl) return;
  meshGroup = ds.Tree.FirstActiveBranch.MeshControlGroup;
  if (!meshGroup) return;
  Assys = pm.assemblies;
  if (!Assys || !Assys.Count) return;
  Assy = Assys.Item(1);

  //finding chamber NbInflation controls-------
  var mehctrls = meshGroup.MeshControls;
  var MeshCtrlObjInfl = null
  for (i = 1; i <= mehctrls.Count; i++) {
    meshctrl = mehctrls.item(i);
    var str1 = new String(meshctrl.Name);
    if ((str1.indexOf("(ch)") != -1)) {
      if (meshctrl.ControlType == ds.Script.id_Inflation) {
        MeshCtrlObjInfl = meshctrl;
        break;
      }
    }
  }

  if (ChInflation==0) {
    if (MeshCtrlObjInfl) {
      if (MeshCtrlObjInfl.SubValue)
        MeshCtrlObjInfl.SubValue = false;
    }
    return;
  }
 
  //Finding ch body
  var protoch;
  var BodychTopId = 0, BodychPartId = 0;
  sm.Clear();
  var nsTopoArr = new Array();
  var nsPartArr = new Array();
  if(IsStraightValveEngine())
    ICGetNSSupports("intf-deck-fluid-ch-lower","",nsTopoArr,nsPartArr);
  else
  {
    ICGetNSSupports("fluid-ch","",nsTopoArr,nsPartArr);
    ICGetNSSupports("fluid-piston","",nsTopoArr,nsPartArr);
  }

  //------------------------------------
  //Creat or reset NbInflation control
  if (sm.SelectedCount) {
    if (!MeshCtrlObjInfl) {
      MeshCtrlObjInfl = meshGroup.AddMeshControl(sm, ds.Script.id_Inflation);
      if (MeshCtrlObjInfl) {
        MeshCtrlGrpNode = ds.Script.GetNode(meshGroup.ID);
        MeshCtrlObjInfl.Name = MeshCtrlObjInfl.Name + " (ch)"
        ds.Script.addNodeAndChildren(MeshCtrlObjInfl, MeshCtrlGrpNode);
      }
    }
    else {
      str1 = MeshCtrlObjInfl.Name;
      MeshCtrlObjInfl.GeometrySelection = sm;
      MeshCtrlObjInfl.Name = str1;
    }
  }
  if(!IsRegen)
  {
    var meshSize = getMeshSize();
    MeshCtrlObjInfl.FirstLayerHeight = meshSize / (4*NbInflation);
  }
  sm.Clear();
  if(IsStraightValveEngine())
  {
    var nsTopoArr2 = new Array();
    var nsPartArr2 = new Array();
    ICGetNSSupports("cyl-quad","",nsTopoArr2,nsPartArr2);
    //Find common edge of cyl-quad and intf-deck-fluid-ch-lower, and assign it as source
    if(nsTopoArr.length ==0)
      return;
    var part = Assy.PartById(nsPartArr[0]);
    var edges, edgesArr=new Array();
    for(var i=0; i<nsTopoArr.length; ++i)
    {
      face = part.BRep.Cell(nsTopoArr[i]);
      edges = face.Edges;
      for(var j=1; j<= edges.Count; ++j)
      {
        edgesArr.push(edges.item(j).Id);
      }
    }
    sm.Clear();
    for(var i=0; i<nsTopoArr2.length; ++i)
    {
      face = part.BRep.Cell(nsTopoArr2[i]);
      edges = face.Edges;
      for(var j=1; j<= edges.Count; ++j)
      {
        if(FindInArray(edgesArr,edges.item(j).Id) > -1)
          sm.AddToSelection(nsPartArr[0], edges.item(j).Id, false);
      }    
    }
  }
  else
  {
    ICGetNSSupports("cyl-tri","",nsTopoArr,nsPartArr);
    ICGetNSSupports("cyl-piston","",nsTopoArr,nsPartArr);
    ICGetNSSupports("cyl-head","",nsTopoArr,nsPartArr);
    ICGetNSSupports("invalve","-ch",nsTopoArr,nsPartArr);
    ICGetNSSupports("exvalve","-ch",nsTopoArr,nsPartArr);
    if(DoesItContainPorts()==0)
      ICGetNSSupports("","-ob-fluid-ch",nsTopoArr,nsPartArr);
  }
  if (MeshCtrlObjInfl&&(sm.SelectedCount>0))
    MeshCtrlObjInfl.SourceGeometry = sm;
}
function ICEngineSetGeometryModified(GeometryModified)
{
  ICSetSessionVaribale("GeometryModified", GeometryModified);
}
function ICConvertPanelStringFormat()
{
  var panel = ICGetSessionVaribale("ICEnginePanel");
  if (panel == "")
    return;
  var str = new String(panel);
  var strs = str.split(";");
  if(strs.length < 1 )
    return;
  if (strs[0] == "SC1") {//sector
    MeshType = strs[1];
    RefSize = strs[2];
    MinMeshSize = strs[3];
    MaxMeshSize = strs[4];
    ChamberBottomMeshSize = strs[5];
    NbInflation = strs[6];
    IsInflationOn = strs[7];
  }
  else if (strs[0] == "V1") { //Port flow
    MeshType = strs[1];
    RefSize = strs[2];
    MinMeshSize = strs[3];
    ProxMinMeshSize = strs[4];
    MaxMeshSize = strs[5];
    NormalAngle = strs[6];
    ProxNumCells = strs[7];
    GrowthRate = strs[8];
    Pinch = strs[9];
    NbInflation = strs[10];
    ChSize = strs[11];
    ChGrowthRate = strs[12];
    ProxValveSize = strs[13];
  }
  else if (strs[0] == "C1") {//cold flow
    MeshType = new String(new Number(strs[1])+1);
    MinMeshSize = strs[2];
    MaxMeshSize = strs[3];
    RefSize = strs[4];
    NormalAngle = strs[5];
    GrowthRate = strs[6];
    Pinch = strs[7];
    NbInflation = strs[8];
    VlayerSize = strs[9];
    IbSize = strs[10];
    IntfVlayerCh = strs[11];
    ChSize = strs[12];
    ChGrowthRate = strs[13];
    VT = strs[14];
    AutoPinch = 1;
    IntfCrevicePiston = getCreviceMeshSize();
    CreviceNoOfLayers = 3;
    if ((isSparkCenterAttrDefined()>0) && (checkSparkActivateAngles() > 0))
      SparkSOI = 1;
    else 
      SparkSOI = 0;
    SoiRadius = round((RefSize * 3.3));
    ChInflation="0";
  }
  else if ((strs[0] == "C2")||(strs[0] == "C3")) {
    if(strs[0] == "C2")
      MeshType = new String(new Number(strs[1])+1);
    else
      MeshType = strs[1];
    MinMeshSize = strs[2];
    MaxMeshSize = strs[3];
    RefSize = strs[4];
    NormalAngle = strs[5];
    GrowthRate = strs[6];
    Pinch = strs[7];
    NbInflation = strs[8];
    VlayerSize = strs[9];
    IbSize = strs[10];
    IntfVlayerCh = strs[11];
    ChSize = strs[12];
    ChGrowthRate = strs[13];
    VT = strs[14];
    AutoPinch = strs[15];
    if ((strs.length > 17) && (strs[0] == "C3"))
    {
      IntfCrevicePiston = strs[16];
      CreviceNoOfLayers = strs[17];
      SparkSOI = strs[18];
      SoiRadius = strs[19];
    }
    else {
      IntfCrevicePiston = getCreviceMeshSize();
      CreviceNoOfLayers = 3;
      if ((isSparkCenterAttrDefined()>0) && (checkSparkActivateAngles() > 0))
        SparkSOI = 1;
      else 
        SparkSOI = 0;
      SoiRadius = round((RefSize * 3.3));
    }
    if(strs.length>20)
      ChInflation = strs[20];
    else
      ChInflation="0";
  }
  else
    return;
  ICSetPanelSessionVarFromGlobalVars();
}
function ICSetPanelSessionVarFromGlobalVars()
{
  var panel="";
  var solver = ICGetSessionVaribale("ICESolver");
  if(solver=="Forte"){
    panel = versionForte + ";MeshType-" + MeshType + ";MinMeshSize-" + MinMeshSize + ";MaxMeshSize-" + MaxMeshSize + ";RefSize-" + RefSize ;
  }    
  else if (IsCombustion()) {
    panel = versionSectorComb + ";MeshType-" + MeshType + ";MinMeshSize-" + MinMeshSize + ";MaxMeshSize-" + MaxMeshSize + ";RefSize-" + RefSize 
    + ";ChamberBottomMeshSize-" + ChamberBottomMeshSize + ";IsInflationOn-" + IsInflationOn + ";NbInflation-" + NbInflation;
  }
  else if (IsPortFlow()) {
    panel = versionColdFlow + ";MeshType-" + MeshType + ";MinMeshSize-" + MinMeshSize + ";MaxMeshSize-" + MaxMeshSize + ";ProxMinMeshSize-" 
    + ProxMinMeshSize +";ProxNumCells-" + ProxNumCells + ";RefSize-" + RefSize + ";NormalAngle-" + NormalAngle + ";GrowthRate-" + GrowthRate 
    + ";Pinch-" + Pinch + ";NbInflation-" + NbInflation + ";ChSize-" + ChSize + ";ChGrowthRate-" + ChGrowthRate +";ProxValveSize-"+ProxValveSize;
  }
  else
  {
    panel = versionColdFlow + ";MeshType-" + MeshType + ";MinMeshSize-" + MinMeshSize + ";MaxMeshSize-" + MaxMeshSize + ";RefSize-" + RefSize 
    + ";NormalAngle-" + NormalAngle + ";GrowthRate-" + GrowthRate + ";Pinch-" + Pinch + ";NbInflation-" + NbInflation + ";VlayerSize-" + VlayerSize 
    + ";IbSize-" + IbSize + ";IntfVlayerCh-" + IntfVlayerCh + ";ChSize-" + ChSize + ";ChGrowthRate-" + ChGrowthRate + ";VT-" + VT + ";AutoPinch-" 
    + AutoPinch + ";IntfCrevicePiston-" + IntfCrevicePiston + ";CreviceNoOfLayers-" + CreviceNoOfLayers + ";SparkSOI-" + SparkSOI + ";SoiRadius-"
    + SoiRadius+";ChInflation-"+ChInflation;
  }
  ICSetSessionVaribale("ICEnginePanel", panel);
}
function ICTokenizeAndLoadXfers(xfer,inpString)
{
  var strs = inpString.split(";");
  for(var i=0; i < strs.length; ++i)
  {
    var strs2 = strs[i].split("-");
    if(strs2.length <2)
      continue;
    xfer(strs2[0])=strs2[1];
  }
}
function ICGetPanelField(field)
{
  var panel = ICGetSessionVaribale("ICEnginePanel");
  var strs = panel.split(";");
  var value="";
  for(var i=0; i < strs.length; ++i)
  {
    var items = strs[i].split("-");
    if(items.length < 2)
      continue;
    if(items[0] == field)
    {
      value = items[1];
      break;
    }
  }
  return value;
}
function ICEWriteSessionVariable(path,varName) {
  var fileSys = AnsObjectFactory.CreateDispatchObject("Scripting.FileSystemObject");
  var textStream = fileSys.CreateTextFile(path, true);
	textStream.WriteLine(ICGetSessionVaribale(varName));
  textStream.Close();
}
function ICAreStringsSameAfterTokenizing(input1,input2,token)
{
  var same=false;
  var strs1 = input1.split(token);
  var strs2 = input2.split(token);
  if(strs1.length == strs2.length)
  {
    var i=0;
    for(i=0; i<strs1.length; ++i)
    {
      if(FindInArray(strs2,strs1[i]) < 0)
        break;
    }
    if(i==strs1.length)
      same=true;
  }
  return same;
}
function ICWriteSettingsFileForAddin()
{
  var DMNSFilePath = ICGetSessionVaribale("DMNSFile");
  var directory = ICGetDirectory(DMNSFilePath);
  if(directory == "")
    return;
  var path =  directory+"ICMeshSettingsPanel.txt";
  ICEWritePanelDefaults(path);
}
//Utility
function ICGetDirectory(fullPath)
{
  var directory="";
  var fullPathCopy = fullPath;
  var separator="\\";
  var index=fullPathCopy.indexOf(separator);
  if(index < 0)
  {
    separator="/";
    index=fullPathCopy.indexOf(separator);
  }
  while(index > -1)
  {
    directory = directory + fullPathCopy.substring(0, index+1);
    fullPathCopy = fullPathCopy.substring(index + 1);
    index=fullPathCopy.indexOf(separator);
  }
  return directory;
}
function  ICEngineResetSolverType()
{
  var branch = ds.Tree.FirstActiveBranch;
  if (!branch)
    return;
  var meshGroup = branch.MeshControlGroup;
  if (!meshGroup)
    return;
  if(meshGroup.PhysicsPreference != 2)
  {
    meshGroup.PhysicsPreference = 2;
    meshGroup.SolverPreference = 0;
    if( (!IsPortFlow()) && (!IsCombustion()) )//Keygrids
      meshGroup.AdvancedSizeFunction = 2;
  }
}
