Making a new directory

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@1 026a22ec-4e7a-0410-994d-e47a0e92e701
PROJECT(ShapeAnalysisModule)

CMAKE_MINIMUM_REQUIRED(VERSION 2.6)

FIND_PACKAGE(ITK REQUIRED)
IF (ITK_FOUND)
  INCLUDE(${ITK_USE_FILE})
ELSE(ITK_FOUND)
	MESSAGE(FATAL_ERROR Please set ITK_DIR.)
ENDIF (ITK_FOUND)

FIND_PACKAGE(VTK REQUIRED)
IF (VTK_FOUND)
  INCLUDE(${VTK_USE_FILE})
ELSE(VTK_FOUND)
	MESSAGE(FATAL_ERROR Please set VTK_DIR.)
ENDIF (VTK_FOUND)

FIND_PACKAGE(GenerateCLP REQUIRED)
IF (GenerateCLP_FOUND)
	INCLUDE(${GenerateCLP_USE_FILE})
ENDIF (GenerateCLP_FOUND)

FIND_PACKAGE(BatchMake REQUIRED)
IF (BatchMake_FOUND)
	INCLUDE(${BatchMake_USE_FILE})
ENDIF (BatchMake_FOUND)

#FIND_PACKAGE(VTK REQUIRED)
#IF(VTK_FOUND)
	#INCLUDE(${VTK_USE_FILE})
#ENDIF(VTK_FOUND)
 
SET (ShapeAnalysisModule_SOURCE 
	ShapeAnalysisModuleCLP.cxx
	Parameters.cxx 
	Parameters.h
	ShapeAnalysisModuleComputation.cxx
	ShapeAnalysisModuleComputation.h
	
) 

GENERATECLP(ShapeAnalysisModule_SOURCE ShapeAnalysisModule.xml)
ADD_EXECUTABLE (ShapeAnalysisModule ${ShapeAnalysisModule_SOURCE})
#INCLUDE_DIRECTORIES("/opt/local/ITK_3.X/Insight_3.16.0/ITK_3.16.0_linux64_dyn/Utilities/itksys ")
# 
TARGET_LINK_LIBRARIES(ShapeAnalysisModule
  itksys
  vtkIO
  ${ITK_LIBRARIES}
  ${BatchMake_LIBRARIES}

)










git-svn-id: https://www.nitrc.org/svn/spharm-pdm@2 026a22ec-4e7a-0410-994d-e47a0e92e701
#ifndef PARAMETERS_H
#define PARAMETERS_H

#include <iostream>
#include <cstring>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <itksys/Process.h>
#include <vector>
#include <dirent.h> 

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkVTKImageIO.h"
#include "itkImageIOBase.h"

#include "vtkPolyDataReader.h"
#include "vtkPolyData.h"
#include "vtkPointSet.h"


#include <string>
#include <stdlib.h>
#include <itksys/Glob.hxx>

using namespace std;

class Parameters
{
  public:
  
	Parameters();
	 ~Parameters();
 
	void ReadFile(const char *_FileName);
	void SetModulePath(char*);
	void SetParameterFile(const char *_ParamFile);
	void SetDataList(vector < vector<string> > _List);

	void SetOutputDirectory(const char *_OutputDirectory);
	void SetChooseInputColumnState(bool inputColumn);
	void SetColumnVolumeFile(int column);
	void SetDataNumber(int _DataNumber);
	void SetEnforcedSpace(float _sx, float _sy, float _sz);
	void SetLabel(double _Label);
	void SetLabelState(bool _LabelState);
	void SetNumberOfIterations(int _NumIter);
	void SetSubdivLevel(int _SubdivLevel);
	void SetSPHARMDegree(int _SPHARMDegree);
	void SetGaussianFilteringState(bool _GaussianFilteringState);
	void SetVarianceBox(int _vx, int _vy, int _vz);
	void SetTemplateState(bool _TemplateState); 
	void SetTemplateMState(bool _TemplateMState);
	void SetFlipTemplate(const char *_FlipTemplate);
	void SetRegTemplate(const char *_FlipTemplate);
	void SetParaOut1State(bool _ParaOut1State);
	void SetParaOut2State(bool _ParaOut2State);
	void SetFinalFlip(int _None_Flip, int _X_Flip, int _Y_Flip, int _Z_Flip, int _XY_Flip, int _YZ_Flip, int _XZ_Flip, int _XYZ_Flip);

	char* GetModulePath();
	vector<string> GetOutputFileHeaders();
	string GetVolumeFileExtension();
	int GetColumnVolumeFile();
	bool GetChooseInputColumnState();
	const char* GetParameterFile();
	int MeanTemplateExist();
	char* GetOutputDirectory();
	int GetDataNumber();
	float GetEnforcedSpaceX();
	float GetEnforcedSpaceY();
	float GetEnforcedSpaceZ();
  	double GetLabel();
	bool GetLabelState();
	int GetNumberOfIterations();
	double GetSubdivLevel();
	int GetSPHARMDegree();

	bool GetGaussianFilteringState();
   
	int GetVarianceBoxX();
	int GetVarianceBoxY();
	int GetVarianceBoxZ();
 
	bool GetTemplateState();
	bool GetTemplateMState();
	char* GetFlipTemplate();
	char* GetRegTemplate(); 
	
	bool GetParaOut1State();
	bool GetParaOut2State();
	
	int GetFinalFlipN();
	int GetFinalFlipX();
	int GetFinalFlipY();
	int GetFinalFlipZ();
	int GetFinalFlipXY();
	int GetFinalFlipYZ();
	int GetFinalFlipXZ();
	int GetFinalFlipXYZ();
 
	string GetNthDataListValue(int line,int column);

	void  SetAllFilesName();
	char* GetAllFilesName(int);
	char* GetAllSurfSPHARMFiles(int);
	char* GetAllSurfSPHARMellalignFiles(int);
	char* GetAllSurfSPHARMprocalignFiles(int);
	char* GetAllPhiFiles(int);
	char* GetAllThetaFiles(int);
	void SetImageDimensions(char*);
	vector <double> GetImageDimensions();
	string GetDirectionToDisplay();

	void SetOverwriteSegPostProcess(bool);
	void SetOverwriteGenParaMesh(bool);
	void SetOverwriteParaToSPHARMMesh(bool);

	bool GetOverwriteSegPostProcess();
	bool GetOverwriteGenParaMesh();
	bool GetOverwriteParaToSPHARMMesh();

	bool DirectoryIsEmpty(const char*);
	
private:
 
	char m_ModulePath[512];
	vector < vector<string> > m_List;
	vector<string> m_OutputFileHeaders;
	char m_FilesName[512];
	char m_MRLMFile[512];
	string m_VolumeFileExtension;
	int m_ColumnVolume;
	bool m_ChooseColumnState;

	int ListSize;
  
	char m_ParamFile[512];
	char m_OutputDirectory[512];

	int m_DataNumber;
	
	float m_sx;
	float m_sy;
	float m_sz;
	
	double m_Label;
	bool m_LabelState;
	int m_NumIter;
	int m_SubdivLevel;
	int m_SPHARMDegree;

	bool m_GaussianFilteringState;
	
	int m_vx;
	int m_vy;
	int m_vz;
	
	bool m_TemplateState;
	bool m_TemplateMState;
	char m_FlipTemplate[512];
	char m_RegTemplate[512];

	bool m_ParaOut1State;
	bool m_ParaOut2State;
	
	int m_None_Flip;
	int m_X_Flip;
	int m_Y_Flip;
	int m_Z_Flip;
	int m_XY_Flip;
	int m_YZ_Flip;
	int m_XZ_Flip;
	int m_XYZ_Flip;

	bool m_OverwriteSegPostProcess;
	bool m_OverwriteGenParaMesh;
	bool m_OverwriteParaToSPHARMMesh;

	string m_directionToDisplay;
	vector<double>m_Dims;

	char** m_AllFilesName; 
	char** surfSPHARM_Files; 
	char** surfSPHARM_ellalign_Files; 
	char** surfSPHARM_procalign_Files; 
	char* Phi_Files; 
	char* Theta_Files;
};

#endif


git-svn-id: https://www.nitrc.org/svn/spharm-pdm@3 026a22ec-4e7a-0410-994d-e47a0e92e701
 #include "Parameters.h"

using namespace std;

 Parameters::Parameters()
 {
 }

Parameters::~Parameters()
 {}


// Set the slicer module path
void Parameters::SetModulePath(char *path)
{
	strcpy(m_ModulePath,path);
	char* p=strrchr(m_ModulePath,'/');
	p[1]='\0';
	strcat(m_ModulePath,"BatchMake_Applications/");
}

// Get the slicer module path
char* Parameters::GetModulePath()
{
	return m_ModulePath;
}

// Read the csv input file
void Parameters::ReadFile(const char *_FileName)
{
	int nbLine=0;
	int column=0;
	int nbColumn=0;	
	bool volumeFileFound=false;
	vector <vector<string> > List;
	
	ifstream file(_FileName);
	string Line;
	
	if(file)
	{
		//read line by line
		while(getline(file,Line))
		{
			istringstream s(Line);
			string value;
			
			vector<string> Data;

			if(!Line.empty())
			{
				while(getline(s,value,','))
				{	
					Data.push_back(value);
					if(nbLine==0)
					{
						m_OutputFileHeaders.push_back(value);// Headers of the input file useed for the ouput file
					}
					if(nbLine==1 && volumeFileFound==false) 
					{	
						if(!m_ChooseColumnState)// the user doesn't choose the input file's column
						{
						char *volume=strchr(value.c_str(),'.');
						if(volume ) //the first volume file is selected automatically
						{
							if(strcmp(volume,".gipl.gz")==0 || strcmp(volume,".gipl")==0 || strcmp(volume,".mka")==0 || strcmp(volume,".mhd")==0 || strcmp(volume,".nrrd") || strcmp(volume,".nhdr")==0 || strcmp(volume,".nii")==0 || strcmp(volume,".nii")==0 || strcmp(volume,".nii.gz")==0 || strcmp(volume,".hdr")==0 || strcmp(volume,".mnc")==0 ) 
							{
								m_ColumnVolume=column;
								m_VolumeFileExtension=volume;
								volumeFileFound=true;
							}
							else 
							{
								cerr<<"Volume file not found in the input file."<<endl;
								exit(0);
							}	
						}	
						}
						else // the user chooses the input file's column to select a volume file
						{
							if(m_ColumnVolume==column) 
							{
								char *volume=strchr(value.c_str(),'.');
								if(volume )
								{
									m_VolumeFileExtension=volume;
									volumeFileFound=true;
								}
								else 
								{
									cerr<<"The column you chose doesn't containt a volume file. Please enter a new column number."<<endl;
									exit(0);
								}
							}
						}
					}
					column++;	
						
				}
				nbLine++;
				nbColumn=column;
				column=0;
				List.push_back(Data);
			}
		}
		SetDataNumber(nbLine-1);	
	}
	else
	{ 
		cerr<<"Error read input File"<<endl;
		exit(0);
	}

	SetDataList(List);
}

// Get the headers of the output file
vector<string> Parameters::GetOutputFileHeaders()
{
	return m_OutputFileHeaders;

}

//create a file with all the names of the generated files
void Parameters::SetParameterFile(const char *_ParamFile)
{
   	std::strcpy(m_ParamFile, _ParamFile);
}

const char* Parameters::GetParameterFile()
{
	return m_ParamFile;
}

string Parameters::GetVolumeFileExtension()
{
	return m_VolumeFileExtension;
}

void Parameters::SetChooseInputColumnState(bool inputColumn)
{
	m_ChooseColumnState=inputColumn;
}

bool Parameters::GetChooseInputColumnState()
{
	return m_ChooseColumnState;
}

void Parameters::SetColumnVolumeFile(int column)
{	
	 m_ColumnVolume=column;
}

int Parameters::GetColumnVolumeFile()
{
	return m_ColumnVolume;
}

void Parameters::SetOutputDirectory(const char *_OutputDirectory)
{
 	 std::strcpy(m_OutputDirectory, _OutputDirectory);
}

char* Parameters::GetOutputDirectory()
{
  	return m_OutputDirectory;
}

void Parameters::SetDataNumber(int _DataNumber)
{
  	m_DataNumber = _DataNumber;
}

int Parameters::GetDataNumber()
{
  	return m_DataNumber;
}

void Parameters::SetEnforcedSpace(float _sx, float _sy, float _sz)
{
	if (_sx >= 0.0)
	{m_sx = _sx;}
	
	if (_sy >= 0.0)
	{m_sy = _sy;}
	
	if (_sz >= 0.0)
	{m_sz = _sz;}
}

float Parameters::GetEnforcedSpaceX()
{
  	return m_sx;
}

float Parameters::GetEnforcedSpaceY()
{
  	return m_sy;
}

float Parameters::GetEnforcedSpaceZ()
{
  	return m_sz;
}

void Parameters::SetLabel(double _Label)
{
  	m_Label = _Label;
}

double Parameters::GetLabel()
{
  	return m_Label;
}

void Parameters::SetLabelState(bool _LabelState)
{
  	m_LabelState = _LabelState;
}

bool Parameters::GetLabelState()
{
  	return m_LabelState;
}

void Parameters::SetNumberOfIterations(int _NumIter)
{
  	m_NumIter = _NumIter;
}

int Parameters::GetNumberOfIterations()
{
  	return m_NumIter;
}

void Parameters::SetSubdivLevel(int _SubdivLevel)
{
  	m_SubdivLevel = _SubdivLevel;
}

double Parameters::GetSubdivLevel()
{
  	return m_SubdivLevel;
}


void Parameters::SetSPHARMDegree(int _SPHARMDegree)
{
  	m_SPHARMDegree = _SPHARMDegree;
}

int Parameters::GetSPHARMDegree()
{
  	return m_SPHARMDegree;
}


void Parameters::SetGaussianFilteringState(bool _GaussianFilteringState)
{
 	 m_GaussianFilteringState = _GaussianFilteringState;
}

bool Parameters::GetGaussianFilteringState()
{
  	return m_GaussianFilteringState;
}

void Parameters::SetVarianceBox(int _vx,int _vy,int _vz)
{
	if (_vx >= 0)
	m_vx = _vx;
	
	if (_vy >= 0)
	m_vy = _vy;
	
	if (_vz >= 0)
	m_vz = _vz;
}

int Parameters::GetVarianceBoxX()
{
  	return m_vx;
}

int Parameters::GetVarianceBoxY()
{
  	return m_vy;
}

int Parameters::GetVarianceBoxZ()
{
  	return m_vz;
}

void Parameters::SetTemplateState(bool _TemplateState)
{
  	m_TemplateState = _TemplateState;
}

bool Parameters::GetTemplateState()
{
  	return m_TemplateState;
}

void Parameters::SetTemplateMState(bool _TemplateMState)
{
  	m_TemplateMState = _TemplateMState;
}

bool Parameters::GetTemplateMState()
{
  	return m_TemplateMState;
}

void Parameters::SetFlipTemplate(const char *_FlipTemplate)
{
  	std::strcpy(m_FlipTemplate, _FlipTemplate);
}

char* Parameters::GetFlipTemplate()
{
  	return m_FlipTemplate;
}

void Parameters::SetRegTemplate(const char *_RegTemplate)
{
  	std::strcpy(m_RegTemplate, _RegTemplate);
}

char* Parameters::GetRegTemplate()
{
  	return m_RegTemplate;
}


void Parameters::SetParaOut1State(bool _ParaOut1State)
{
  	m_ParaOut1State = _ParaOut1State;
}
bool Parameters::GetParaOut1State()
{
  	return m_ParaOut1State;
}

void Parameters::SetParaOut2State(bool _ParaOut2State)
{
  	m_ParaOut2State = _ParaOut2State;
}

bool Parameters::GetParaOut2State()
{
  	return m_ParaOut2State;
}

void Parameters::SetFinalFlip(int _None_Flip, int _X_Flip, int _Y_Flip, int _Z_Flip, int _XY_Flip, int _YZ_Flip, int _XZ_Flip, int _XYZ_Flip)
{
	m_None_Flip = _None_Flip;
	m_X_Flip = _X_Flip;
	m_Y_Flip = _Y_Flip;
	m_Z_Flip = _Z_Flip;
	m_XY_Flip = _XY_Flip;
	m_YZ_Flip = _YZ_Flip;
	m_XZ_Flip = _XZ_Flip;
	m_XYZ_Flip = _XYZ_Flip;
}

int Parameters::GetFinalFlipN()
{
  	return m_None_Flip;
}

int Parameters::GetFinalFlipX()
{
  	return m_X_Flip;
}

int Parameters::GetFinalFlipY()
{
  	return m_Y_Flip;
}

int Parameters::GetFinalFlipZ()
{
  	return m_Z_Flip;
}

int Parameters::GetFinalFlipXY()
{
  	return m_XY_Flip;
}

int Parameters::GetFinalFlipYZ()
{
  	return m_YZ_Flip;
}

int Parameters::GetFinalFlipXZ()
{
  	return m_XZ_Flip;
}

int Parameters::GetFinalFlipXYZ()
{
  	return m_XYZ_Flip;
}

//Set Data list containing all the data from csv file
void Parameters::SetDataList(vector < vector<string> > _List)
{	
		m_List=_List;
}

int Parameters::MeanTemplateExist()
{
	itksys::Glob glob;
	
	std::vector<std::string> Mean;
	std::string Expression = GetOutputDirectory();
	Expression.insert(Expression.size(),"/Template/*meanAll.vtk");
	glob.RecurseOn();
	glob.FindFiles(Expression);
	Mean = glob.GetFiles();
	
	return Mean.size();
}

//Get data value
string Parameters::GetNthDataListValue(int line,int column)
{
		string file;
		file=m_List[line][column];
		return file;
}

// Set the dimension of the first object to display it in a MRML scene
void Parameters::SetImageDimensions(char *filename)
{
	//read vtk file
	vtkPolyDataReader *meshin = vtkPolyDataReader::New();
	meshin->SetFileName(filename);
	
	try{
		meshin->Update();		
	}
	catch(...)
	{
		std::cout << "Cannot open file: " << filename << " to set dimensions" << std::endl;
		return ;
	}

	vtkPolyData *poly= vtkPolyData::New();
	poly=meshin->GetOutput();
	vtkIdType idNumPointsInFile=poly->GetNumberOfPoints();

	vtkPoints * pts;
	double minCoord[3];
	double maxCoord[3];

	double *firstCoord;
	

	//find the max and min coordinates
	pts=poly->GetPoints();
	firstCoord=pts->GetPoint(0);

	minCoord[0]=firstCoord[0];
	minCoord[1]=firstCoord[1];
	minCoord[2]=firstCoord[2];

	maxCoord[0]=firstCoord[0];
	maxCoord[1]=firstCoord[1];
	maxCoord[2]=firstCoord[2];

  	for(unsigned int i = 1; i < idNumPointsInFile; i++)
   	{	
		double *p;
		p=pts->GetPoint(i);
	
		if(p[0]<=minCoord[0])
		{
			minCoord[0]=p[0];
		}
		
		if(p[1]<=minCoord[1])
		{
			minCoord[1]=p[1];
		}
	
		if(p[2]<=minCoord[2])
		{
			minCoord[2]=p[2];
		}
	
		if(p[0]>=maxCoord[0])
		{
			maxCoord[0]=p[0];
		}
	
		if(p[1]>=maxCoord[1])
		{
			maxCoord[1]=p[1];
		}
	
		if(p[2]>=maxCoord[2])
		{
			maxCoord[2]=p[2];
		}
    	}
	
	m_Dims.clear();

	//find the biggest dimension
	m_Dims.push_back(maxCoord[0]-minCoord[0]);
	m_Dims.push_back(maxCoord[1]-minCoord[1]);
	m_Dims.push_back(maxCoord[2]-minCoord[2]);

	if(m_Dims[0]<m_Dims[1])
	{
		if(m_Dims[1]<m_Dims[2])
			m_directionToDisplay="ZYX";
		else
		{
			if(m_Dims[0]<m_Dims[2])
				m_directionToDisplay="YZX";
			else 	m_directionToDisplay="YXZ";
		}
	}

	else
	{
		if(m_Dims[0]<m_Dims[2])
			m_directionToDisplay="ZXY";
		else
		{
			if(m_Dims[1]<m_Dims[2])
				m_directionToDisplay="XZY";
			else	 m_directionToDisplay="XYZ";
		}			
	}
}

vector <double> Parameters::GetImageDimensions()
{
	return m_Dims;
}

string Parameters::GetDirectionToDisplay()
{
	return m_directionToDisplay;
}

//Set the names of all the files containninb by the input files 
void Parameters::SetAllFilesName()
{	

	int DataNumber=GetDataNumber();
	m_AllFilesName = new char *[DataNumber];

	for(int i=0;i<DataNumber;i++)
	{	
		m_AllFilesName[i] = new char[512];
		char c[512];
		char *file;
	
		std::strcpy(c,GetNthDataListValue(i+1,GetColumnVolumeFile()).c_str());
		file=std::strrchr(c,'/');

		for(unsigned int j=0;j<strlen(file);j++)
		{
			file[j]=file[j+1];
			if(file[j]=='.')
				file[j]='\0';
		}
		std::strcpy(m_AllFilesName[i],file);
	}
}

char* Parameters::GetAllFilesName(int i)
{
	return m_AllFilesName[i];
}

void Parameters::SetOverwriteSegPostProcess(bool overwrite)
{
	m_OverwriteSegPostProcess=overwrite;
}

bool Parameters::GetOverwriteSegPostProcess()
{
	return m_OverwriteSegPostProcess;
}

void Parameters::SetOverwriteGenParaMesh(bool overwrite)
{
	m_OverwriteGenParaMesh=overwrite;
}

bool Parameters::GetOverwriteGenParaMesh()
{
	return m_OverwriteGenParaMesh;
}

void Parameters::SetOverwriteParaToSPHARMMesh(bool overwrite)
{
	m_OverwriteParaToSPHARMMesh=overwrite;
}

bool Parameters::GetOverwriteParaToSPHARMMesh()
{
	return m_OverwriteParaToSPHARMMesh;
}

//To know if the directory is empty or not
bool Parameters::DirectoryIsEmpty(const char * path)
{
	DIR *dir=opendir(path);
	struct dirent *mydir;
	int nbFiles=-2;

	if(dir!=NULL)
	{
		while((mydir=readdir(dir))!=NULL)
		{
			nbFiles++;

		}
	}
	else{ cerr<<" Cannot read the directory "<<path<<endl;}
	if(nbFiles==0)
		return true;
	else
		return false;
}

//Get all the names of the SPHARM files
char* Parameters::GetAllSurfSPHARMFiles(int ind)
{
	int DataNumber=GetDataNumber();
	surfSPHARM_Files = new char *[DataNumber];

	for(int i=0;i<DataNumber;i++)
	{	
		surfSPHARM_Files[i] = new char[512];
		std::strcpy(surfSPHARM_Files[i],GetOutputDirectory());
		std::strcat(surfSPHARM_Files[i],"/Mesh/SPHARM/");
		std::strcat(surfSPHARM_Files[i],GetAllFilesName(i));
		std::strcat(surfSPHARM_Files[i],"_pp_surfSPHARM.vtk");
	}
	return surfSPHARM_Files[ind];
}

//Get all the names of the SPHARM ellalign files
char* Parameters::GetAllSurfSPHARMellalignFiles(int ind)
{
	int DataNumber=GetDataNumber();
	surfSPHARM_ellalign_Files = new char *[DataNumber];

	for(int i=0;i<DataNumber;i++)
	{	
		surfSPHARM_ellalign_Files[i] = new char[512];
		std::strcpy(surfSPHARM_ellalign_Files[i],GetOutputDirectory());
		std::strcat(surfSPHARM_ellalign_Files[i],"/Mesh/SPHARM/");
		std::strcat(surfSPHARM_ellalign_Files[i],GetAllFilesName(i));
		std::strcat(surfSPHARM_ellalign_Files[i],"_pp_surfSPHARM_ellalign.vtk");
	}
	return surfSPHARM_ellalign_Files[ind];
}

//Get all the names of the SPHARM procalign files
char* Parameters::GetAllSurfSPHARMprocalignFiles(int ind)
{
	int DataNumber=GetDataNumber();
	surfSPHARM_procalign_Files = new char *[DataNumber];

	for(int i=0;i<DataNumber;i++)
	{	
		surfSPHARM_procalign_Files[i] = new char[512];
		std::strcpy(surfSPHARM_procalign_Files[i],GetOutputDirectory());
		std::strcat(surfSPHARM_procalign_Files[i],"/Mesh/SPHARM/");
		std::strcat(surfSPHARM_procalign_Files[i],GetAllFilesName(i));
		std::strcat(surfSPHARM_procalign_Files[i],"_pp_surfSPHARM_procalign.vtk");
	}
	return surfSPHARM_procalign_Files[ind];
}

//Get all the names of the phi files
char* Parameters::GetAllPhiFiles(int ind)
{
	Phi_Files = new char[512];
	char c[512];
	char *file;
	
	std::strcpy(c,GetNthDataListValue(1,GetColumnVolumeFile()).c_str());
	file=std::strrchr(c,'/');

	for(unsigned int j=0;j<strlen(file);j++)
	{
		file[j]=file[j+1];
		if(file[j]=='.')
			file[j]='\0';
	}
	std::strcpy(Phi_Files,GetOutputDirectory());
	std::strcat(Phi_Files,"/Template/");
	std::strcat(Phi_Files,file);
	std::strcat(Phi_Files,"_pp_surf_paraPhi.txt");
	return Phi_Files;
}

//Get all the names of the theta files
char* Parameters::GetAllThetaFiles(int ind)
{
	Theta_Files = new char[512];
	char c[512];
	char *file;
	
	std::strcpy(c,GetNthDataListValue(1,GetColumnVolumeFile()).c_str());
	file=std::strrchr(c,'/');

	for(unsigned int j=0;j<strlen(file);j++)
	{
		file[j]=file[j+1];
		if(file[j]=='.')
			file[j]='\0';
	}
	std::strcpy(Theta_Files,GetOutputDirectory());
	std::strcat(Theta_Files,"/Template/");
	std::strcat(Theta_Files,file);
	std::strcat(Theta_Files,"_pp_surf_paraTheta.txt");
	return Theta_Files;
}


git-svn-id: https://www.nitrc.org/svn/spharm-pdm@4 026a22ec-4e7a-0410-994d-e47a0e92e701
#include "ShapeAnalysisModuleCLP.h"
#include "ShapeAnalysisModuleComputation.h"
#include "Parameters.h"

using namespace std;
// int main(int argc, char * argv [])
// {
//    	PARSE_ARGS; 
// 	cout<<"------ Shape Analysis Module start -----"<<endl;
// 	
// 	ShapeAnalysisModuleComputation m_computation;
// 
// 	m_computation.SetModulePath(argv[0]);
// 	m_computation.SetChooseInputColumnState(inputColumn);
// 	if(inputColumn) m_computation.SetColumnVolumeFile(columVolumeFile);
// 	
// 	m_computation.SetParameterFile(GroupeProjectInputFile.c_str());
// 	m_computation.SetOutputDirectory(GroupeProjectOutputDirectory.c_str());
// 	m_computation.ReadFile(m_computation.GetParameterFile());
// 	
// 	m_computation.SetOverwriteSegPostProcess(OverwriteSegPostProcess);
// 	m_computation.SetOverwriteGenParaMesh(OverwriteGenParaMesh);
// 	m_computation.SetOverwriteParaToSPHARMMesh(OverwriteParaToSPHARMMesh);
//  	m_computation.SetEnforcedSpace(sx,sy,sz);
// 	m_computation.SetLabelState(LabelState);
// 	m_computation.SetLabel(ValueLabelNumber);
// 	m_computation.SetNumberOfIterations(NumberofIterations);
// 	m_computation.SetSubdivLevel(SubdivLevelValue);
// 	m_computation.SetSPHARMDegree(SPHARMDegreeValue);
// 	
// 	m_computation.SetGaussianFilteringState(GaussianFiltering);
// 	if(GaussianFiltering)
// 		m_computation.SetVarianceBox(VarianceX,VarianceY,VarianceZ);
// 
//  	m_computation.SetTemplateState(Template);
// 	if(Template)
// 	{
// 		m_computation.SetFlipTemplate(flipTemplate.c_str());
//    		m_computation.SetRegTemplate(regTemplate.c_str());
// 	}
// 
// 	m_computation.SetTemplateMState(MTemplate);
// 	m_computation.SetParaOut1State(ParaOut1Template);
// 
// 	if(NoFLip) m_computation.SetFinalFlip(1,0,0,0,0,0,0,0);
// 	else if(FlipALongAxisX) m_computation.SetFinalFlip(0,1,0,0,0,0,0,0);
// 	else if (FlipALongAxisY) m_computation.SetFinalFlip(0,0,1,0,0,0,0,0);
// 	else if (FlipALongAxisZ) m_computation.SetFinalFlip(0,0,0,1,0,0,0,0);
// 	else if (FlipALongAxisXandY) m_computation.SetFinalFlip(0,0,0,0,1,0,0,0);
// 	else if (FlipALongAxisYandZ) m_computation.SetFinalFlip(0,0,0,0,0,1,0,0);
// 	else if (FlipALongAxisXandZ) m_computation.SetFinalFlip(0,0,0,0,0,0,1,0);
// 	else if (FlipALongAxisXandYandZ) m_computation.SetFinalFlip(0,0,0,0,0,0,0,1);
// 	
// 	m_computation.Computation();
// 
// 	return EXIT_SUCCESS ;
// }

int main(int argc, char * argv [])
{

	cout<<"------ Shape Analysis Module start -----"<<endl;
	ShapeAnalysisModuleComputation m_computation;
	m_computation.SetModulePath("/home/hamelc/ShapeAnalysisTool/build64/ShapeAnalysisModule");
	m_computation.SetChooseInputColumnState(false);
	m_computation.SetColumnVolumeFile(5);
	//m_computation.SetParameterFile("../ShapeAnalysisTest/ShapeLocal/Output/ShapeAnalysisModule_OutputFile.csv");
	m_computation.SetParameterFile("/home/hamelc/ShapeAnalysisTool/InputFile.csv");
	m_computation.SetOutputDirectory("/home/hamelc/ShapeAnalysisTool/ShapeAnalysisTest/ShapeLocal2");
	m_computation.ReadFile(m_computation.GetParameterFile());
	
	m_computation.SetOverwriteSegPostProcess(true);
 	m_computation.SetOverwriteGenParaMesh(true);
 	m_computation.SetOverwriteParaToSPHARMMesh(true);
	
 	m_computation.SetEnforcedSpace(0.5,0.5,0.5);

	m_computation.SetLabelState(false);
	m_computation.SetLabel(1);


	m_computation.SetNumberOfIterations(1);
	m_computation.SetSubdivLevel(11);
	m_computation.SetSPHARMDegree(15);
	
	m_computation.SetGaussianFilteringState(true);
	m_computation.SetVarianceBox(12,12,12);

	m_computation.SetTemplateState(false);
	m_computation.SetFlipTemplate("/home/hamelc/ShapeAnalysisModule/ShapeAnalysisTest/test_surfSPHARM.coef");
	m_computation.SetRegTemplate("/home/hamelc/ShapeAnalysisModule/ShapeAnalysisTest/test_surfSPHARM.vtk");
	m_computation.SetTemplateMState(false);

	m_computation.SetParaOut1State(true);

	m_computation.SetFinalFlip(1,0,0,0,0,0,0,0);
	
	m_computation.Computation();

	return EXIT_SUCCESS ;
}



git-svn-id: https://www.nitrc.org/svn/spharm-pdm@5 026a22ec-4e7a-0410-994d-e47a0e92e701
#include "ShapeAnalysisModuleComputation.h"

ShapeAnalysisModuleComputation::ShapeAnalysisModuleComputation()
: Parameters()
{}

ShapeAnalysisModuleComputation::~ShapeAnalysisModuleComputation()
{}


// Compute Shape Analysis
void ShapeAnalysisModuleComputation::Computation()
{
	std::cout<<"\n\nComputing ShapeAnalysisModule..."<<std::endl<<std::endl;

	SetBMSShapeAnalysisModuleFile(false);
	SetBMSShapeAnalysisModuleMRMLFile(false);
	SetAllFilesName();
	OverWrite();

	WriteBMSShapeAnalysisModuleFile();
 	ExecuteBatchMake(GetBMSShapeAnalysisModuleFile());

	if(GetTemplateMState()==true)
	{
		ComputationMean();
		WriteBMSShapeAnalysisModuleFile2();
		ExecuteBatchMake(GetBMSShapeAnalysisModuleFile2());
	}
 
	// execute MeshMath external application
	for(int i=0;i<GetDataNumber();i++)
	{
 		ExecuteMeshMath(i,"phi");
		ExecuteMeshMath(i,"theta");
	}
	
 	WriteBMSMRMLScene();
 	ExecuteBatchMake(GetBMSShapeAnalysisModuleMRMLFile());
 	SetBMSShapeAnalysisModuleFile(true);

	std::cout<<"Computing ShapeAnalysisModule: Done!"<<std::endl<<std::endl;
  
  	return;
}

//Execute MeshMath to write a KWM scalar field (1D) into a PolyData Field Data Scalar to visualize in Slicer3
void ShapeAnalysisModuleComputation::ExecuteMeshMath(int numData, char * scalar)
{

//execute MeshMath for each volume file: Original, Ellalign, Procalign
for(int j=0;j<3;j++)
{

  std::vector<const char*> args;  
  char* data = NULL;
  int length;
  double timeout = 0.05;
  int result;
  char *fileType=NULL;

  args.push_back("MeshMath");

  if(j==0) fileType=GetAllSurfSPHARMFiles(numData);
  else if (j==1) fileType=GetAllSurfSPHARMellalignFiles(numData);
  else if (j==2) fileType=GetAllSurfSPHARMprocalignFiles(numData);
  
  args.push_back(fileType);
  args.push_back(fileType);
  args.push_back("-KWMtoPolyData");

  if(scalar=="phi")
  {  
    args.push_back(GetAllPhiFiles(0));
    args.push_back("Color Map Phi");
  }
  if(scalar=="theta")
  { 
    args.push_back(GetAllThetaFiles(0));
    args.push_back("Color Map Theta");
  }

  args.push_back(0);

  // Run the application
  itksysProcess* gp = itksysProcess_New();
  itksysProcess_SetCommand(gp, &*args.begin());
  itksysProcess_SetOption(gp,itksysProcess_Option_HideWindow,1);
  itksysProcess_Execute(gp);


  while(int Value = itksysProcess_WaitForData(gp,&data,&length,&timeout)) // wait for 1s
  {
    if ( ((Value == itksysProcess_Pipe_STDOUT) || (Value == itksysProcess_Pipe_STDERR)) && data[0]=='D' )
    {
	strstream st;
      	for(int i=0;i<length;i++) 	
	{
		st<<data[i];
	}
	string dim=st.str();
	istringstream s(dim);
	string value;
			
	while(getline(s,value,' '))
	{	
		m_Dims.push_back((atoi(value.c_str()))/2);		
	}
	
	m_Dims.erase(m_Dims.begin());
    }
    	timeout = 0.05;   	
  }

  itksysProcess_WaitForExit(gp, 0);
  
  result = 1;
  switch(itksysProcess_GetState(gp))
  {
  case itksysProcess_State_Exited:
  {
    result = itksysProcess_GetExitValue(gp);
  } break;
  case itksysProcess_State_Error:
  {
    std::cerr<<"Error: Could not run " << args[0]<<":\n";
    std::cerr<<itksysProcess_GetErrorString(gp)<<"\n";
    std::cout<<"Error: Could not run " << args[0]<<":\n";
    std::cout<<itksysProcess_GetErrorString(gp)<<"\n";
  } break;
  case itksysProcess_State_Exception:
  {
    std::cerr<<"Error: "<<args[0]<<" terminated with an exception: "<<itksysProcess_GetExceptionString(gp)<<"\n";
    std::cout<<"Error: "<<args[0]<<" terminated with an exception: "<<itksysProcess_GetExceptionString(gp)<<"\n";
  } break;
  case itksysProcess_State_Starting:
  case itksysProcess_State_Executing:
  case itksysProcess_State_Expired:
  case itksysProcess_State_Killed:
  {
    // Should not get here.
    std::cerr<<"Unexpected ending state after running "<<args[0]<<std::endl;
    std::cout<<"Unexpected ending state after running "<<args[0]<<std::endl;
  } break;
  }
  itksysProcess_Delete(gp);  

}
}
// Create BMS File to compute the SPHARM pipeline
void ShapeAnalysisModuleComputation::SetBMSShapeAnalysisModuleFile(bool changeDirectory)
{
	std::strcpy(m_BMSShapeAnalysisModuleFile, GetOutputDirectory());
	
	if(changeDirectory==false)
		std::strcat(m_BMSShapeAnalysisModuleFile, "/");

	else std::strcat(m_BMSShapeAnalysisModuleFile, "/BatchMake_Scripts/");

	std::strcat(m_BMSShapeAnalysisModuleFile, "ShapeAnalysisModule.bms");

	return;  
}

 // Get BMS File
char *ShapeAnalysisModuleComputation::GetBMSShapeAnalysisModuleFile()
{
  	return m_BMSShapeAnalysisModuleFile;
}


// Create BMS for mean computation File
void ShapeAnalysisModuleComputation::SetBMSShapeAnalysisModuleFile2(bool changeDirectory)
{
	std::strcpy(m_BMSShapeAnalysisModuleFile, GetOutputDirectory());
	
	if(changeDirectory==false)
		std::strcat(m_BMSShapeAnalysisModuleFile, "/");

	else std::strcat(m_BMSShapeAnalysisModuleFile, "/BatchMake_Scripts/");

	std::strcat(m_BMSShapeAnalysisModuleFile, "ShapeAnalysisModule_MeanAsTemplate.bms");

	return;  
}

// Get BMS File for mean computation
char *ShapeAnalysisModuleComputation::GetBMSShapeAnalysisModuleFile2()
{
  	return m_BMSShapeAnalysisModuleFile;
}

// Create a BMS file to create a MRML scene
void ShapeAnalysisModuleComputation::SetBMSShapeAnalysisModuleMRMLFile(bool changeDirectory)
{
	std::strcpy(m_BMSShapeAnalysisModuleMRLMFile, GetOutputDirectory());
	std::strcat(m_BMSShapeAnalysisModuleMRLMFile, "/");
	std::strcat(m_BMSShapeAnalysisModuleMRLMFile, "ShapeAnalysisModuleMRML.bms");
}

char * ShapeAnalysisModuleComputation::GetBMSShapeAnalysisModuleMRMLFile()
{
	return m_BMSShapeAnalysisModuleMRLMFile;
}

//create the output file
void ShapeAnalysisModuleComputation::SetOuputFile()
{
	std::strcpy(m_OutputFile, GetOutputDirectory());
	std::strcat(m_OutputFile, "/Output/");
	std::strcat(m_OutputFile, "ShapeAnalysisModule_OutputFile.csv");
}

char * ShapeAnalysisModuleComputation::GetOutputFile()
{
	return m_OutputFile;
}

 // Execute BatchMake script
void ShapeAnalysisModuleComputation::ExecuteBatchMake(char *_Input)
{
  	std::cout<<"\tExecuting BatchMake..."<<std::endl;

	char * envpath = getenv("BatchmakeShapeAnalysisModule_Dir");
	std::string applicationPath;
	bm::ScriptParser m_Parser;

	// the module path exist
	if(chdir(GetModulePath())==0)
	{	
		//if bmm files are in the same directory as the Shape Analysis Module
		m_Parser.LoadWrappedApplication(GetModulePath());
	}

	else
	{
		// if the environment variable is set
		if (envpath) 
		{	
			applicationPath = std::string(envpath);
			m_Parser.LoadWrappedApplication(applicationPath.c_str());
		}

		else
		{
			std::cerr<<"The environment variable 'BatchmakeShapeAnalysisModule_Dir' needs to be set"<<std::endl;
			std::cerr<<"bash usage : export BatchmakeShapeAnalysisModule_Dir=<Batchmake ShapeAnalysisModule Directory>"<<std::endl;
			std::cerr<<"tcsh usage : setenv BatchmakeShapeAnalysisModule_Dir <Batchmake ShapeAnalysisModule Directory>"<<std::endl;
			exit(0);
		}
	}
		
	
	bool ComputationSuccess = m_Parser.Execute(_Input);
	if (!ComputationSuccess)
		cerr<<"\tExecuting BatchMake: Error!"<<endl;

 	 std::cout<<"\tExecuting BatchMake: Done!"<<std::endl<<endl;
  return;
}

// Write the BMS script to create a MRML file
void ShapeAnalysisModuleComputation::WriteBMSMRMLScene()
{
	SetAllFilesName();

	std::ofstream BMSShapeAnalysisModuleMRML(m_BMSShapeAnalysisModuleMRLMFile);
	
	BMSShapeAnalysisModuleMRML<<"  echo()"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  echo(\t'Wrting MRML scripts...')"<<std::endl;
	for(int count=0;count<3;count++)
	{
		BMSShapeAnalysisModuleMRML<<"  # Script to create a MRML scene"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  MakeDirectory("<<GetOutputDirectory()<<"/MRML)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<" Set(FileDir '"<<GetOutputDirectory()<<"/Mesh/SPHARM')"<<std::endl;
	
	// create a MRML file with all the original SPHARM files
	if(count==0)
	{
		char *firstFile1;
		firstFile1 = new char[512];
		std::strcpy(firstFile1,GetAllSurfSPHARMFiles(0));
		
		vector<double>Dims;
		SetImageDimensions(firstFile1);
		Dims=GetImageDimensions();
		BMSShapeAnalysisModuleMRML<<" ListFileInDir(MRMLfiles ${FileDir} *SPHARM.vtk)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(MRMLScene "<<GetOutputDirectory()<<"/MRML/ShapeAnalysisModuleMRMLScene.mrml)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim0 "<<Dims[0]<<")"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim1 "<<Dims[1]<<")"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim2 "<<Dims[2]<<")"<<std::endl;

	}
	//create a MRML files with all the SPHARM ellalign files
	else if(count==1)
	{
		char *firstFile2;
		firstFile2 = new char[512];
		std::strcpy(firstFile2,GetAllSurfSPHARMellalignFiles(0));
		
		vector<double>Dims;
		SetImageDimensions(firstFile2);
		Dims=GetImageDimensions();
		BMSShapeAnalysisModuleMRML<<" ListFileInDir(MRMLfiles ${FileDir} *SPHARM_ellalign.vtk)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(MRMLScene "<<GetOutputDirectory()<<"/MRML/ShapeAnalysisModuleMRMLScene_ellalign.mrml)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim0 "<<Dims[0]<<")"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim1 "<<Dims[1]<<")"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim2 "<<Dims[2]<<")"<<std::endl;
	}
	//create a MRML file with all the procalign files
	else if(count==2)
	{
		char *firstFile3;
		firstFile3 = new char[512];
		std::strcpy(firstFile3,GetAllSurfSPHARMprocalignFiles(0));
		//std::strcat(firstFile3,"_pp_surfSPHARM_procalign.vtk");
		
		vector<double>Dims;
		SetImageDimensions(firstFile3);
		Dims=GetImageDimensions();
		BMSShapeAnalysisModuleMRML<<" ListFileInDir(MRMLfiles ${FileDir} *SPHARM_procalign.vtk)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(MRMLScene "<<GetOutputDirectory()<<"/MRML/ShapeAnalysisModuleMRMLScene_procalign.mrml)"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim0 "<<Dims[0]<<")"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim1 "<<Dims[1]<<")"<<std::endl;
		BMSShapeAnalysisModuleMRML<<"  Set(dim2 "<<Dims[2]<<")"<<std::endl;
	}
	BMSShapeAnalysisModuleMRML<<"  WriteFile(${MRMLScene} '<MRML userTags=\"\">\\n')"<<std::endl;
	for(int j=0;j<3;j++)
	{
	if(j==1)
	{
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<SceneSnapshot\\n')"<<std::endl;
 	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSceneSnapshotNode1\" name=\"Color Map Phi\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\">\\n')"<<std::endl;
	}
	else if(j==2)
	{
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<SceneSnapshot\\n')"<<std::endl;
 	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSceneSnapshotNode1\" name=\"Color Map Theta\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\">\\n')"<<std::endl;
	}
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Selection\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSelectionNode1\" name=\"vtkMRMLSelectionNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" activeVolumeID=\"NULL\" secondaryVolumeID=\"NULL\" activeLabelVolumeID=\"NULL\" activeFiducialListID=\"NULL\" activeROIListID=\"NULL\" activeCameraID=\"NULL\" activeViewID=\"NULL\" activeLayoutID=\"vtkMRMLLayoutNode1\"></Selection>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Interaction\\n' )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLInteractionNode1\" name=\"vtkMRMLInteractionNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" currentInteractionMode=\"ViewTransform\" lastInteractionMode=\"ViewTransform\"></Interaction>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Layout\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLayoutNode1\" name=\"vtkMRMLLayoutNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" currentViewArrangement=\"2\" guiPanelVisibility=\"1\" bottomPanelVisibility =\"1\" guiPanelLR=\"0\" numberOfCompareViewRows=\"0\" numberOfCompareViewColumns=\"0\" numberOfLightboxRows=\"1\" numberOfLightboxColumns=\"1\" mainPanelSize=\"400\" secondaryPanelSize=\"400\"></Layout>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<View\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLViewNode1\" name=\"vtkMRMLViewNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" active=\"false\" fieldOfView=\"200\" letterSize=\"0.05\" boxVisible=\"true\" fiducialsVisible=\"true\" fiducialLabelsVisible=\"true\" axisLabelsVisible=\"true\" backgroundColor=\"0.70196 0.70196 0.90588\" animationMode=\"Off\" viewAxisMode=\"LookFrom\" spinDegrees=\"2\" spinMs=\"5\" spinDirection=\"YawLeft\" rotateDegrees=\"5\" rockLength=\"200\" rockCount=\"0\" stereoType=\"NoStereo\" renderMode=\"Perspective\"></View>\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Camera\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLCameraNode1\" name=\"vtkMRMLCameraNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" position=\"-726.497 88.984 13.4559\" focalPoint=\"0 0 0\" viewUp=\"0 0 1\" parallelProjection=\"false\" parallelScale=\"1\" active=\"false\"></Camera>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<TGParameters\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLChangeTrackerNode1\" name=\"vtkMRMLChangeTrackerNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" ROIMin=\"-1 -1 -1\" ROIMax=\"-1 -1 -1\" SegmentThresholdMin=\"-1\" SegmentThresholdMax=\"-1\" Analysis_Intensity_Flag=\"0\" Analysis_Deformable_Flag=\"0\" UseITK=\"1\"></TGParameters>\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<VolumeRenderingSelection\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLVolumeRenderingSelectionNode1\" name=\"vtkMRMLVolumeRenderingSelectionNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" activeVolumeID=\"NULL\" activeVolumeRenderingID=\"NULL\"></VolumeRenderingSelection>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Slice\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSliceNode1\" name=\"Green\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" fieldOfView=\"387.5 250 1\" dimensions=\"496 320 1\" activeSlice=\"0\" layoutGridRows=\"1\" layoutGridColumns=\"1\" sliceToRAS=\"-1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\" layoutName=\"Green\" orientation=\"Coronal\" jumpMode=\"1\" sliceVisibility=\"false\" widgetVisibility=\"false\" useLabelOutline=\"false\" sliceSpacingMode=\"0\" prescribedSliceSpacing=\"1 1 1\"></Slice>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<SliceComposite\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSliceCompositeNode1\" name=\"vtkMRMLSliceCompositeNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" backgroundVolumeID=\"\" foregroundVolumeID=\"\" labelVolumeID=\"\" compositing=\"0\" labelOpacity=\"1\" linkedControl=\"0\" foregroundGrid=\"0\" backgroundGrid=\"0\" labelGrid=\"1\" fiducialVisibility=\"1\" fiducialLabelVisibility=\"1\" sliceIntersectionVisibility=\"0\" layoutName=\"Green\" annotationMode=\"All\" doPropagateVolumeSelection=\"1\"></SliceComposite>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Slice\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSliceNode2\" name=\"Red\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" fieldOfView=\"386.719 250 1\" dimensions=\"495 320 1\" activeSlice=\"0\" layoutGridRows=\"1\" layoutGridColumns=\"1\" sliceToRAS=\"-1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1\" layoutName=\"Red\" orientation=\"Axial\" jumpMode=\"1\" sliceVisibility=\"false\" widgetVisibility=\"false\" useLabelOutline=\"false\" sliceSpacingMode=\"0\" prescribedSliceSpacing=\"1 1 1\"></Slice>\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<SliceComposite\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSliceCompositeNode2\" name=\"vtkMRMLSliceCompositeNode2\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" backgroundVolumeID=\"\" foregroundVolumeID=\"\" labelVolumeID=\"\" compositing=\"0\" labelOpacity=\"1\" linkedControl=\"0\" foregroundGrid=\"0\" backgroundGrid=\"0\" labelGrid=\"1\" fiducialVisibility=\"1\" fiducialLabelVisibility=\"1\" sliceIntersectionVisibility=\"0\" layoutName=\"Red\" annotationMode=\"All\" doPropagateVolumeSelection=\"1\"></SliceComposite>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Slice\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSliceNode3\" name=\"Yellow\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" fieldOfView=\"386.719 250 1\" dimensions=\"495 320 1\" activeSlice=\"0\" layoutGridRows=\"1\" layoutGridColumns=\"1\" sliceToRAS=\"0 0 1 0 -1 0 0 0 0 1 0 0 0 0 0 1\" layoutName=\"Yellow\" orientation=\"Sagittal\" jumpMode=\"1\" sliceVisibility=\"false\" widgetVisibility=\"false\" useLabelOutline=\"false\" sliceSpacingMode=\"0\" prescribedSliceSpacing=\"1 1 1\"></Slice>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<SliceComposite\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLSliceCompositeNode3\" name=\"vtkMRMLSliceCompositeNode3\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" backgroundVolumeID=\"\" foregroundVolumeID=\"\" labelVolumeID=\"\" compositing=\"0\" labelOpacity=\"1\" linkedControl=\"0\" foregroundGrid=\"0\" backgroundGrid=\"0\" labelGrid=\"1\" fiducialVisibility=\"1\" fiducialLabelVisibility=\"1\" sliceIntersectionVisibility=\"0\" layoutName=\"Yellow\" annotationMode=\"All\" doPropagateVolumeSelection=\"1\"></SliceComposite>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Crosshair\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLCrosshairNode1\" name=\"vtkMRMLCrosshairNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" crosshairMode=\"NoCrosshair\" crosshairBehavior=\"Normal\" crosshairThickness=\"Fine\" crosshairRAS=\"0 0 0\"></Crosshair>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<ClipModels\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLClipModelsNode1\" name=\"vtkMRMLClipModelsNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" clipType=\"0\" redSliceClipState=\"0\" yellowSliceClipState=\"0\" greenSliceClipState=\"0\"></ClipModels>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<ScriptedModule\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLScriptedModuleNode1\" name=\"vtkMRMLScriptedModuleNode1\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" ModuleName =\"Editor\" parameter0= \"label 1\"></ScriptedModule>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(Dim1 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count3 1)"<<std::endl;

	BMSShapeAnalysisModuleMRML<<"  ForEach(files ${MRMLfiles})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  GetParam(data ${files} '${count2}' )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<ModelStorage\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLModelStorageNode'${count}'\" name=\"vtkMRMLModelStorageNode'${count}'\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" fileName=\""<<GetOutputDirectory()<<"/Mesh/SPHARM/'${data}'\" useCompression=\"1\" readState=\"0\" writeState=\"0\"></ModelStorage>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Randomize(Rvalue uniform 0 1) "<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Randomize(Gvalue uniform 0 1) "<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Randomize(Bvalue uniform 0 1) "<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<ModelDisplay\\n')"<<std::endl;
	if(j==0)
	{
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLModelDisplayNode'${count}'\" name=\"vtkMRMLModelDisplayNode'${count}'\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" color=\"'${Rvalue}' '${Gvalue}' '${Bvalue}'\" selectedColor=\"1 0 0\" selectedAmbient=\"0.4\" ambient=\"0.18\" diffuse=\"0.82\" selectedSpecular=\"0.5\" specular=\"0.16\" power=\"1\" opacity=\"1\" visibility=\"true\" clipping=\"false\" sliceIntersectionVisibility=\"false\" backfaceCulling=\"true\" scalarVisibility=\"false\" vectorVisibility=\"false\" tensorVisibility=\"false\" autoScalarRange=\"true\" scalarRange=\"0 100\" colorNodeRef=\"vtkMRMLColorTableNodeFullRainbow\" activeScalarName=\"\" ></ModelDisplay>\\n')"<<std::endl;
	}
	else if(j==1)
	{
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLModelDisplayNode'${count}'\" name=\"vtkMRMLModelDisplayNode'${count}'\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" color=\"'${Rvalue}' '${Gvalue}' '${Bvalue}'\" selectedColor=\"1 0 0\" selectedAmbient=\"0.4\" ambient=\"0.18\" diffuse=\"0.82\" selectedSpecular=\"0.5\" specular=\"0.16\" power=\"1\" opacity=\"1\" visibility=\"true\" clipping=\"false\" sliceIntersectionVisibility=\"false\" backfaceCulling=\"true\" scalarVisibility=\"true\" vectorVisibility=\"false\" tensorVisibility=\"false\" autoScalarRange=\"true\" scalarRange=\"0 100\" colorNodeRef=\"vtkMRMLColorTableNodeFullRainbow\" activeScalarName=\"Color Map Phi\" ></ModelDisplay>\\n')"<<std::endl;
	}
	else if(j==2)
	{
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLModelDisplayNode'${count}'\" name=\"vtkMRMLModelDisplayNode'${count}'\" hideFromEditors=\"true\" selectable=\"true\" selected=\"false\" color=\"'${Rvalue}' '${Gvalue}' '${Bvalue}'\" selectedColor=\"1 0 0\" selectedAmbient=\"0.4\" ambient=\"0.18\" diffuse=\"0.82\" selectedSpecular=\"0.5\" specular=\"0.16\" power=\"1\" opacity=\"1\" visibility=\"true\" clipping=\"false\" sliceIntersectionVisibility=\"false\" backfaceCulling=\"true\" scalarVisibility=\"true\" vectorVisibility=\"false\" tensorVisibility=\"false\" autoScalarRange=\"true\" scalarRange=\"0 100\" colorNodeRef=\"vtkMRMLColorTableNodeFullRainbow\" activeScalarName=\"Color Map Theta\" ></ModelDisplay>\\n')"<<std::endl;
	}
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<Model\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLModelNode'${count}'\" name=\""<<GetOutputDirectory()<<"/Mesh/SPHARM/'${data}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" transformNodeRef=\"vtkMRMLLinearTransformNode'${count}'\" storageNodeRef=\"vtkMRMLModelStorageNode'${count}'\" userTags=\"\" displayNodeRef=\"vtkMRMLModelDisplayNode'${count}'\"></Model>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '<LinearTransform\\n')"<<std::endl;


	if(GetDirectionToDisplay()=="XYZ")
	{
	BMSShapeAnalysisModuleMRML<<"  Math(Dim0 ${dim0} * ${count2})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim1 ${dim1} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLinearTransformNode'${count}'\" name=\"vtkMRMLLinearTransformNode'${count}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" userTags=\"\" matrixTransformToParent=\"1 0 0 '${Dim0}'  0 1 0 '${Dim1}'  0 0 1 0  0 0 0 1\"></LinearTransform>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} != 10)"<<std::endl; //only 10 objects per line
 	BMSShapeAnalysisModuleMRML<<"  Inc(${count2} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} == 10)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim1 ${dim1} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${count3} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	}

	else if(GetDirectionToDisplay()=="XZY")
	{
	BMSShapeAnalysisModuleMRML<<"  Math(Dim0 ${dim0} * ${count2})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim1 ${dim1} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLinearTransformNode'${count}'\" name=\"vtkMRMLLinearTransformNode'${count}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" userTags=\"\" matrixTransformToParent=\"1 0 0 '${Dim0}'  0 1 0 0  0 0 1 '${Dim2}'  0 0 0 1\"></LinearTransform>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} != 10)"<<std::endl; //only 10 objects per line
 	BMSShapeAnalysisModuleMRML<<"  Inc(${count2} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} == 10)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim2 ${dim2} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${count3} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	}

	else if(GetDirectionToDisplay()=="YXZ")
	{
	BMSShapeAnalysisModuleMRML<<"  Math(Dim1 ${dim1} * ${count2})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim2 ${dim2} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLinearTransformNode'${count}'\" name=\"vtkMRMLLinearTransformNode'${count}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" userTags=\"\" matrixTransformToParent=\"1 0 0 '${Dim0}'  0 1 0 '${Dim1}'  0 0 1 0  0 0 0 1\"></LinearTransform>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} != 10)"<<std::endl; //only 10 objects per line
 	BMSShapeAnalysisModuleMRML<<"  Inc(${count2} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} == 10)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim0 ${dim0} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${count3} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	}

	else if(GetDirectionToDisplay()=="YZX")
	{
	BMSShapeAnalysisModuleMRML<<"  Math(Dim1 ${dim1} * ${count2})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim2 ${dim2} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLinearTransformNode'${count}'\" name=\"vtkMRMLLinearTransformNode'${count}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" userTags=\"\" matrixTransformToParent=\"1 0 0 0  0 1 0 '${Dim1}'  0 0 1 '${Dim2}'  0 0 0 1\"></LinearTransform>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} != 10)"<<std::endl; //only 10 objects per line
 	BMSShapeAnalysisModuleMRML<<"  Inc(${count2} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} == 10)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim2 ${dim2} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${count3} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;

	}

	else if(GetDirectionToDisplay()=="ZXY")
	{
	BMSShapeAnalysisModuleMRML<<"  Math(Dim2 ${dim2} * ${count2})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim0 ${dim0} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLinearTransformNode'${count}'\" name=\"vtkMRMLLinearTransformNode'${count}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" userTags=\"\" matrixTransformToParent=\"1 0 0 '${Dim0}'  0 1 0 0  0 0 1 '${Dim2}'  0 0 0 1\"></LinearTransform>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} != 10)"<<std::endl; //only 10 objects per line
 	BMSShapeAnalysisModuleMRML<<"  Inc(${count2} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} == 10)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim0 ${dim0} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${count3} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	}

	else if(GetDirectionToDisplay()=="ZYX")
	{
	BMSShapeAnalysisModuleMRML<<"  Math(Dim2 ${dim2} * ${count2})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim0 ${dim0} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} 'id=\"vtkMRMLLinearTransformNode'${count}'\" name=\"vtkMRMLLinearTransformNode'${count}'\" hideFromEditors=\"false\" selectable=\"true\" selected=\"false\" userTags=\"\" matrixTransformToParent=\"1 0 0 0  0 1 0 '${Dim1}'  0 0 1 '${Dim2}'  0 0 0 1\"></LinearTransform>\\n')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} != 10)"<<std::endl; //only 10 objects per line
 	BMSShapeAnalysisModuleMRML<<"  Inc(${count2} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  If( ${res} == 10)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Math(Dim1 ${dim1} * ${count3} )"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(count2 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${count3} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Set(res 0)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndIf( ${res} )"<<std::endl;
	}

	BMSShapeAnalysisModuleMRML<<"  Inc(${count} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  Inc(${res} 1)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  EndForEach(files)"<<std::endl;
	if(j==1 || j==2)
	{
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '</SceneSnapshot>\\n')"<<std::endl;
	}
	}
	BMSShapeAnalysisModuleMRML<<"  AppendFile(${MRMLScene} '</MRML>\\n')"<<std::endl;
	}
	
	BMSShapeAnalysisModuleMRML<<" Set(BMSFile "<<GetOutputDirectory()<<"/BatchMake_Scripts/ShapeAnalysisModuleMRML.bms)"<<std::endl;
	BMSShapeAnalysisModuleMRML<<" CopyFile("<<GetBMSShapeAnalysisModuleMRMLFile()<<" ${BMSFile})"<<std::endl;
	BMSShapeAnalysisModuleMRML<<" DeleteFile("<<GetBMSShapeAnalysisModuleMRMLFile()<<")"<<std::endl;

	BMSShapeAnalysisModuleMRML<<"  echo(\t'Wrting MRML script: Done!')"<<std::endl;
	BMSShapeAnalysisModuleMRML<<"  echo()"<<std::endl;
	return;
}
 
 // Write Batchmake script to compute Shape Analysis
void ShapeAnalysisModuleComputation::WriteBMSShapeAnalysisModuleFile()
{

std::ofstream BMSShapeAnalysisModuleFile(GetBMSShapeAnalysisModuleFile());
vector<string> OutputFileHeaders=GetOutputFileHeaders();
int DataNumber;

BMSShapeAnalysisModuleFile<<"#---------------------------- Shape Analysis ----------------------------"<<std::endl;
BMSShapeAnalysisModuleFile<<"#------------------------------------------------------------------------"<<std::endl;
BMSShapeAnalysisModuleFile<<"#------------------------------------------------------------------------"<<std::endl;
BMSShapeAnalysisModuleFile<<"#------------------------------------------------------------------------"<<std::endl;

//Set the headers for the output file
for(unsigned int i=0;i<OutputFileHeaders.size();i++)
{
	BMSShapeAnalysisModuleFile<<" Set(Header"<<i<<" '"<<GetNthDataListValue(1,i)<<"')"<<std::endl;

}

BMSShapeAnalysisModuleFile<<"set (OrigCasesList '"<<GetNthDataListValue(1,GetColumnVolumeFile())<<"')"<<std::endl;

std::cout<<"Number of Datas: "<<GetDataNumber()<<std::endl;

for (DataNumber = 2; DataNumber <=GetDataNumber(); DataNumber++)
{

for(unsigned int i=0;i<OutputFileHeaders.size();i++)
{
BMSShapeAnalysisModuleFile<<"set (Header"<<i<<" ${Header"<<i<<"} '" <<GetNthDataListValue(DataNumber,i)<<"')"<<std::endl;

}
BMSShapeAnalysisModuleFile<<"set (OrigCasesList ${OrigCasesList} '"<<GetNthDataListValue(DataNumber,GetColumnVolumeFile())<<"')"<<std::endl;
}
BMSShapeAnalysisModuleFile<<""<<std::endl;

BMSShapeAnalysisModuleFile<<"#Create directories"<<std::endl;
BMSShapeAnalysisModuleFile<<"MakeDirectory("<<GetOutputDirectory()<<"/BatchMake_Scripts/)"<<std::endl;
BMSShapeAnalysisModuleFile<<"MakeDirectory("<<GetOutputDirectory()<<"/Mesh/)"<<std::endl;
BMSShapeAnalysisModuleFile<<"MakeDirectory("<<GetOutputDirectory()<<"/Mesh/PostProcess/)"<<std::endl;
BMSShapeAnalysisModuleFile<<"MakeDirectory("<<GetOutputDirectory()<<"/Mesh/SPHARM/)"<<std::endl;
BMSShapeAnalysisModuleFile<<"MakeDirectory("<<GetOutputDirectory()<<"/Template/)"<<std::endl; 
BMSShapeAnalysisModuleFile<<"MakeDirectory("<<GetOutputDirectory()<<"/Output/)"<<std::endl; 
BMSShapeAnalysisModuleFile<<"set(BMSdir '"<<GetOutputDirectory()<<"/BatchMake_Scripts')"<<std::endl;
BMSShapeAnalysisModuleFile<<"set(datadir '"<<GetOutputDirectory()<<"/')"<<std::endl;
BMSShapeAnalysisModuleFile<<"set(PPdir '"<<GetOutputDirectory()<<"/Mesh/PostProcess/')"<<std::endl;
BMSShapeAnalysisModuleFile<<"set(SPHARMdir '"<<GetOutputDirectory()<<"/Mesh/SPHARM/')"<<std::endl;
BMSShapeAnalysisModuleFile<<"set(tdir '"<<GetOutputDirectory()<<"/Template/')"<<std::endl;
BMSShapeAnalysisModuleFile<<"set(Outputdir '"<<GetOutputDirectory()<<"/Output/')"<<std::endl;
BMSShapeAnalysisModuleFile<<"echo()"<<std::endl;

BMSShapeAnalysisModuleFile<<"#Create OutputFile"<<std::endl;
//BMSShapeAnalysisModuleFile<<"Set(OutputFile "<<GetOutputDirectory()<<"/Output/ShapeAnalysisModule_OutputFile.csv)"<<std::endl;
SetOuputFile();
BMSShapeAnalysisModuleFile<<"Set(OutputFile "<<GetOutputFile()<<")"<<std::endl;

BMSShapeAnalysisModuleFile<<" WriteFile(${OutputFile} '"<<OutputFileHeaders[0]<<",')"<<std::endl;
for(unsigned int i=1;i<OutputFileHeaders.size();i++)
{
	BMSShapeAnalysisModuleFile<<" appendFile(${OutputFile} '"<<OutputFileHeaders[i]<<",')"<<std::endl;
}

//Write headers of the output file
BMSShapeAnalysisModuleFile<<" appendFile(${OutputFile} ' Post Processed Segmentation, Parametrisation of Original Surface, SPHARM Surface in Original Space, SPHARM Coefficient in Original Space, SPHARM Surface in Ellipsoid Aligned Space, SPHARM Coefficient in Ellipsoid Aligned Space, SPHARM Surface in Procaligned Space\\n')"<<std::endl;
BMSShapeAnalysisModuleFile<<"echo()"<<std::endl;


BMSShapeAnalysisModuleFile<<"  Set(count 0)"<<std::endl;

BMSShapeAnalysisModuleFile<<""<<std::endl;
BMSShapeAnalysisModuleFile<<"ForEach(case ${OrigCasesList})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  #Extract basename"<<std::endl;
BMSShapeAnalysisModuleFile<<"  GetFilename(basename ${case} NAME_WITHOUT_EXTENSION)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo(Case: ${case})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testSeg ${PPdir} *${basename}*_pp"<<GetVolumeFileExtension()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testGen1 ${SPHARMdir} *${basename}*para.vtk*) "<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testGen2 ${SPHARMdir} *${basename}*surf.vtk*) "<<std::endl;
BMSShapeAnalysisModuleFile<<"  set(testGen ${testGen1} ${testGen2}) "<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testPara ${SPHARMdir} *${basename}*SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testPara2 ${SPHARMdir} *${basename}*MeanSPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testtemp ${tdir}  *SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testtemp2 ${tdir} *${basename}*SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  "<<std::endl;
BMSShapeAnalysisModuleFile<<"  set(ppcase ${PPdir}${basename}_pp.gipl.gz)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  "<<std::endl;

BMSShapeAnalysisModuleFile<<"  #Post Processing"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo('Doing Post Processing')"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${testSeg} == '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetApp(Seg @SegPostProcessCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Seg.fileName ${case})"<<std::endl;

if (GetGaussianFilteringState()==true)
 {
BMSShapeAnalysisModuleFile<<"    SetAppOption(Seg.gaussianOn 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Seg.variance_vect.variance_vect "<<GetVarianceBoxX()<<","<<GetVarianceBoxY()<<","<<GetVarianceBoxZ()<<")"<<std::endl;
 }
BMSShapeAnalysisModuleFile<<"    SetAppOption(Seg.outfileName ${ppcase})"<<std::endl;
if (GetLabelState()==true)
{
BMSShapeAnalysisModuleFile<<"    SetAppOption(Seg.label.label "<<GetLabel()<<")"<<std::endl;
}
BMSShapeAnalysisModuleFile<<"    SetAppOption(Seg.spacing_vect.spacing_vect "<<GetEnforcedSpaceX()<<","<<GetEnforcedSpaceY()<<","<<GetEnforcedSpaceZ()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Run(output ${Seg} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('SegPostProcess Error:' ${error}')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${testSeg})"<<std::endl;
BMSShapeAnalysisModuleFile<<""<<std::endl;

BMSShapeAnalysisModuleFile<<"  #GenParaMesh"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo('Doing GenParaMesh')"<<std::endl;
BMSShapeAnalysisModuleFile<<"  Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  foreach(data ${testGen})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if (${value} < 2)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetApp(Gen @GenParaMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Gen.infile ${ppcase})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Gen.outParaName ${SPHARMdir}${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Gen.outSurfName ${SPHARMdir}${basename}_pp_surf.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Gen.numIterations.numIterations "<<GetNumberOfIterations()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Gen.label.label 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Run(output ${Gen} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('GenParaMesh Error:' ${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<""<<std::endl;

BMSShapeAnalysisModuleFile<<"  #ParaToSPHARMMesh"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo('Doing ParaToSPHARMMesh')"<<std::endl;

if (GetTemplateState()==false)
 {
BMSShapeAnalysisModuleFile<<"  Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  foreach(data ${testtemp})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if (${value} < 4)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  #Create Template"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('Creating Template')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetApp(ParaT @ParaToSPHARMMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.inSurfFile ${SPHARMdir}${basename}_pp_surf.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.inParaFile ${SPHARMdir}${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.outbase ${tdir}${basename}_pp_surf)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.subdivLevel.subdivLevel "<<GetSubdivLevel()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.spharmDegree.spharmDegree "<<GetSPHARMDegree()<<")"<<std::endl;
if (GetFinalFlipN()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex "<<0<<")"<<std::endl;}
if (GetFinalFlipX()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<4<<")"<<std::endl;}
if (GetFinalFlipY()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<5<<")"<<std::endl;}
if (GetFinalFlipZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<7<<")"<<std::endl;}
if (GetFinalFlipXY()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<1<<")"<<std::endl;}
if (GetFinalFlipYZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<2<<")"<<std::endl;}
if (GetFinalFlipXZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<3<<")"<<std::endl;}
if (GetFinalFlipXYZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.finalFlipIndex.finalFlipIndex  "<<6<<")"<<std::endl;}

if (GetParaOut1State()==true)
 {
BMSShapeAnalysisModuleFile<<"    SetAppOption(ParaT.writePara 1)"<<std::endl;
 }
BMSShapeAnalysisModuleFile<<"    Run(output ${ParaT} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('ParaToSPHARMMesh: '${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<" DeleteFile("<<GetOutputDirectory()<<"/Template/${basename}_pp_surf_paraPhiHalf.txt)"<<std::endl;
BMSShapeAnalysisModuleFile<<" DeleteFile("<<GetOutputDirectory()<<"/Template/${basename}_pp_surf_paraMix.txt)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  "<<std::endl;


if (GetTemplateMState()==true) 
{
if (MeanTemplateExist()==0)
{
BMSShapeAnalysisModuleFile<<"    Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    foreach(data ${testPara2})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    if (${value} < 4) "<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(reg ${tdir} *SPHARM.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(flip ${tdir} *SPHARM.coef)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(regTemplate ${reg})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(flipTemplate ${flip})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('regTemplate: '${regTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('flipTemplate: '${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      #The Template is the first data"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      foreach(data ${testPara})"<<std::endl;
BMSShapeAnalysisModuleFile<<"        Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      if (${value} < 5)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetApp(Para @ParaToSPHARMMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.inSurfFile ${SPHARMdir}${basename}_pp_surf.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.inParaFile ${SPHARMdir}${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.outbase  ${SPHARMdir}${basename}_pp_surf)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.flipTemplateFile.flipTemplateFile ${tdir}${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.subdivLevel.subdivLevel "<</*m_Parameters.*/GetSubdivLevel()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.spharmDegree.spharmDegree "<</*m_Parameters.*/GetSPHARMDegree()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.regTemplateFile.regTemplateFile ${tdir}${regTemplate})"<<std::endl;
if (GetFinalFlipN()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<0<<")"<<std::endl;}
if (GetFinalFlipX()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<4<<")"<<std::endl;}
if (GetFinalFlipY()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<5<<")"<<std::endl;}
if (GetFinalFlipZ()==1){
BMSShapeAnalysisModuleFile<<"    	   SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<7<<")"<<std::endl;}
if (GetFinalFlipXY()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<1<<")"<<std::endl;}
if (GetFinalFlipYZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<2<<")"<<std::endl;}
if (GetFinalFlipXZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<3<<")"<<std::endl;}
if (GetFinalFlipXYZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<6<<")"<<std::endl;}

if (GetParaOut1State()==true)
{
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.writePara 1)"<<std::endl;
}
BMSShapeAnalysisModuleFile<<"        Run(output ${Para} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('ParaToSPHARMMesh: '${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      endif(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    endif(${value})"<<std::endl;
ComputeMean = 1;
}
if (MeanTemplateExist()!=0)
{
ComputeMean = 0;
BMSShapeAnalysisModuleFile<<"    listFileInDir(deletelist ${SPHARMdir} ${basename}*SPHARM*) "<<std::endl;  
BMSShapeAnalysisModuleFile<<"    Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    foreach(data ${testPara2})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    if (${value} < 4) "<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(reg ${tdir} *meanAll.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(regTemplate ${reg})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(flip ${tdir} *SPHARM.coef)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(flipTemplate ${flip})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('regTemplate: '${regTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('flipTemplate: '${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      #The Template is the Mean"<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(testPara ${SPHARMdir} ${basename}*SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetApp(Para @ParaToSPHARMMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.inSurfFile ${SPHARMdir}${basename}_pp_surf.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.inParaFile ${SPHARMdir}${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.outbase  ${SPHARMdir}${basename}_pp_surf_tMean)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.flipTemplateFile.flipTemplateFile ${tdir}${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.subdivLevel.subdivLevel "<</*m_Parameters.*/GetSubdivLevel()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.spharmDegree.spharmDegree "<</*m_Parameters.*/GetSPHARMDegree()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.regTemplateFile.regTemplateFile ${tdir}${regTemplate})"<<std::endl;
if (GetFinalFlipN()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<0<<")"<<std::endl;}
if (GetFinalFlipX()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<4<<")"<<std::endl;}
if (GetFinalFlipY()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<5<<")"<<std::endl;}
if (GetFinalFlipZ()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<7<<")"<<std::endl;}
if (GetFinalFlipXY()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<1<<")"<<std::endl;}
if (GetFinalFlipYZ()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<2<<")"<<std::endl;}
if (GetFinalFlipXZ()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<3<<")"<<std::endl;}
if (GetFinalFlipXYZ()==1){
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<6<<")"<<std::endl;}
 
if (GetParaOut1State()==true)
 {
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.writePara 1)"<<std::endl;
 }
BMSShapeAnalysisModuleFile<<"      Run(output ${Para} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('ParaToSPHARMMesh: '${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    endif(${value})"<<std::endl;

}
}
if (GetTemplateMState()==false)
{
BMSShapeAnalysisModuleFile<<"    Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    foreach(data ${testPara2})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    if (${value} < 4) "<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(reg ${tdir} *SPHARM.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(flip ${tdir} *SPHARM.coef)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(regTemplate ${reg})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(flipTemplate ${flip})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('regTemplate: '${regTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('flipTemplate: '${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      #The Template is the first data"<<std::endl;
BMSShapeAnalysisModuleFile<<"      Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      foreach(data ${testPara})"<<std::endl;
BMSShapeAnalysisModuleFile<<"        Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      if (${value} < 4)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetApp(Para @ParaToSPHARMMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.inSurfFile ${SPHARMdir}${basename}_pp_surf.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.inParaFile ${SPHARMdir}${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.outbase  ${SPHARMdir}${basename}_pp_surf)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.flipTemplateFile.flipTemplateFile ${tdir}${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.subdivLevel.subdivLevel "<<GetSubdivLevel()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.spharmDegree.spharmDegree "<<GetSPHARMDegree()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.regTemplateFile.regTemplateFile ${tdir}${regTemplate})"<<std::endl;
if (GetFinalFlipN()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<0<<")"<<std::endl;}
if (GetFinalFlipX()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<4<<")"<<std::endl;}
if (GetFinalFlipY()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<5<<")"<<std::endl;}
if (GetFinalFlipZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<7<<")"<<std::endl;}
if (GetFinalFlipXY()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<1<<")"<<std::endl;}
if (GetFinalFlipYZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<2<<")"<<std::endl;}
if (GetFinalFlipXZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<3<<")"<<std::endl;}
if (GetFinalFlipXYZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<6<<")"<<std::endl;}

if (GetParaOut1State()==true)
{
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.writePara 1)"<<std::endl;
}
BMSShapeAnalysisModuleFile<<"        Run(output ${Para} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('ParaToSPHARMMesh: '${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      endif(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    endif(${value})"<<std::endl;
 }
 }
if (GetTemplateState()==true)
 {
BMSShapeAnalysisModuleFile<<"  #The Template is choosed by the user"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo ('regTemplate: '"<<GetRegTemplate()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo ('flipTemplate: '"<<GetFlipTemplate()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  Set(value 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  foreach(data ${testPara})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Inc(${value} 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    Int(${value})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndForEach(data)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if (${value} < 4)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetApp(Para @ParaToSPHARMMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.inSurfFile ${SPHARMdir}${basename}_pp_surf.meta)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.inParaFile ${SPHARMdir}${basename}_pp_para.meta)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.outbase  ${SPHARMdir}${basename}_pp_surf)"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.flipTemplateFile.flipTemplateFile "<<GetFlipTemplate()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.subdivLevel.subdivLevel "<<GetSubdivLevel()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.spharmDegree.spharmDegree "<<GetSPHARMDegree()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.regTemplateFile.regTemplateFile "<<GetRegTemplate()<<")"<<std::endl;
if (GetFinalFlipN()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<0<<")"<<std::endl;}
if (GetFinalFlipX()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<4<<")"<<std::endl;}
if (GetFinalFlipY()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<5<<")"<<std::endl;}
if (GetFinalFlipZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<7<<")"<<std::endl;}
if (GetFinalFlipXY()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<1<<")"<<std::endl;}
if (GetFinalFlipYZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<2<<")"<<std::endl;}
if (GetFinalFlipXZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<3<<")"<<std::endl;}
if (GetFinalFlipXYZ()==1){
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<6<<")"<<std::endl;}
 
if (GetParaOut1State()==true)
 {
BMSShapeAnalysisModuleFile<<"    SetAppOption(Para.writePara 1)"<<std::endl;
 }
BMSShapeAnalysisModuleFile<<"    Run(output ${Para} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('ParaToSPHARMMesh: '${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${value})"<<std::endl;

}
BMSShapeAnalysisModuleFile<<"Set(paraPhiHalf "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surf_paraPhiHalf.txt)"<<std::endl;
BMSShapeAnalysisModuleFile<<"FileExists(testParaPhiHalf ${paraPhiHalf})"<<std::endl; 
BMSShapeAnalysisModuleFile<<"If( ${testParaPhiHalf} == 1 )"<<std::endl;
BMSShapeAnalysisModuleFile<<"echo(${paraPhiHalf})"<<std::endl;
BMSShapeAnalysisModuleFile<<" DeleteFile(${paraPhiHalf})"<<std::endl;
BMSShapeAnalysisModuleFile<<"EndIf(${testParaPhiHalf})"<<std::endl;

BMSShapeAnalysisModuleFile<<"Set(paraMix "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surf_paraMix.txt)"<<std::endl;
BMSShapeAnalysisModuleFile<<"FileExists(testParaMix ${paraMix})"<<std::endl; 
BMSShapeAnalysisModuleFile<<"If( ${testParaMix} == 1 )"<<std::endl;
BMSShapeAnalysisModuleFile<<" DeleteFile(${paraMix})"<<std::endl;
BMSShapeAnalysisModuleFile<<"EndIf(${testParaMix})"<<std::endl;
//Write the Ouput File
BMSShapeAnalysisModuleFile<<"  #Write Ouput File"<<std::endl;

for(unsigned int i=0;i<OutputFileHeaders.size();i++)
{
BMSShapeAnalysisModuleFile<<"  GetParam(header"<<i<<" ${Header"<<i<<"} ${count})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${header"<<i<<"} ',' )"<<std::endl;
}
BMSShapeAnalysisModuleFile<<"  Inc(${count} 1)"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(postProcessFile "<<GetOutputDirectory()<<"/Mesh/PostProcess/${basename}_pp"<<GetVolumeFileExtension()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"  FileExists(testPostProcessFile ${postProcessFile})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  If(${testPostProcessFile} == 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${postProcessFile} ',')"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndIf(${testPostProcessFile})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  If(${testPostProcessFile} == 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} 'none,')"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndIf(${testPostProcessFile})"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(originSurf "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${originSurf} ',')"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(surfSPHARM "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surfSPHARM.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${surfSPHARM} ',')"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(surfSPHARMcoef "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surfSPHARM.coef)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${surfSPHARMcoef} ',')"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(surfSPHARM_ellalign "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surfSPHARM_ellalign.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${surfSPHARM_ellalign} ',')"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(surfSPHARM_ellalignCoef "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surfSPHARM_ellalign.coef)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${surfSPHARM_ellalignCoef} ',')"<<std::endl;

BMSShapeAnalysisModuleFile<<"  Set(procalignFile "<<GetOutputDirectory()<<"/Mesh/SPHARM/${basename}_pp_surfSPHARM_procalign.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  FileExists(testProcalignFile ${procalignFile})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  If(${testProcalignFile} == 1)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} ${procalignFile} )"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndIf(${testProcalignFile})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  If(${testProcalignFile} == 0)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} 'none')"<<std::endl;
BMSShapeAnalysisModuleFile<<"  EndIf(${testProcalignFile})"<<std::endl;

BMSShapeAnalysisModuleFile<<"  appendFile(${OutputFile} '\\n' )"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"EndForEach(case)"<<std::endl;
BMSShapeAnalysisModuleFile<<""<<std::endl<<std::endl;

BMSShapeAnalysisModuleFile<<" Set(BMSFile ${BMSdir}"<<"/ShapeAnalysisModule.bms"<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<" CopyFile("<<GetBMSShapeAnalysisModuleFile()<<" ${BMSdir})"<<std::endl;
BMSShapeAnalysisModuleFile<<" DeleteFile("<<GetBMSShapeAnalysisModuleFile()<<")"<<std::endl;

return;
}  

//Write BMS file for mean computation
void ShapeAnalysisModuleComputation::WriteBMSShapeAnalysisModuleFile2()
{

std::ofstream BMSShapeAnalysisModuleFile(GetBMSShapeAnalysisModuleFile2());

BMSShapeAnalysisModuleFile<<"#----- Shape Analysis Computing ParaToSPHARMMesh with mean as input -----"<<std::endl;
BMSShapeAnalysisModuleFile<<"#------------------------------------------------------------------------"<<std::endl;
BMSShapeAnalysisModuleFile<<"#------------------------------------------------------------------------"<<std::endl;
BMSShapeAnalysisModuleFile<<"#------------------------------------------------------------------------"<<std::endl;

BMSShapeAnalysisModuleFile<<"echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"echo('Computing with mean as a template')"<<std::endl;
BMSShapeAnalysisModuleFile<<"echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"set (OrigCasesList '"<<GetNthDataListValue(1,GetColumnVolumeFile())<<"')"<<std::endl;

int DataNumber;
for (DataNumber = 2; DataNumber <=GetDataNumber(); DataNumber++)
{
BMSShapeAnalysisModuleFile<<"set (OrigCasesList ${OrigCasesList} '"<<GetNthDataListValue(DataNumber,GetColumnVolumeFile())<<"')"<<std::endl;
}
BMSShapeAnalysisModuleFile<<""<<std::endl;

BMSShapeAnalysisModuleFile<<"set(SPHARMdir '"<<GetOutputDirectory()<<"/Mesh/SPHARM/')"<<std::endl;
BMSShapeAnalysisModuleFile<<"set(tdir '"<<GetOutputDirectory()<<"/Template/')"<<std::endl;

BMSShapeAnalysisModuleFile<<"ForEach(case ${OrigCasesList})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  #Extract basename"<<std::endl;
BMSShapeAnalysisModuleFile<<"  GetFilename(basename ${case} NAME_WITHOUT_EXTENSION)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  echo('Case: '${case})"<<std::endl;
BMSShapeAnalysisModuleFile<<"  "<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testPara ${SPHARMdir} *${basename}*SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testPara2 ${SPHARMdir} *${basename}*MeanSPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testtemp ${tdir}  *SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  listFileInDir(testtemp2 ${tdir} *${basename}*SPHARM*)"<<std::endl;



BMSShapeAnalysisModuleFile<<"    if (${value} < 4) "<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(reg ${tdir} *meanAll.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(regTemplate ${reg})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(flip ${tdir} *SPHARM.coef)"<<std::endl;
BMSShapeAnalysisModuleFile<<"      set(flipTemplate ${flip})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('regTemplate : '${regTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo ('flipTemplate : '${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"      echo()"<<std::endl;
BMSShapeAnalysisModuleFile<<"      #The Template is the Mean"<<std::endl;
BMSShapeAnalysisModuleFile<<"      listFileInDir(testPara ${SPHARMdir} ${basename}*SPHARM*)"<<std::endl;
BMSShapeAnalysisModuleFile<<"       SetApp(Para @ParaToSPHARMMeshCLP)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.inSurfFile ${SPHARMdir}${basename}_pp_surf.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.inParaFile ${SPHARMdir}${basename}_pp_para.vtk)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.outbase  ${SPHARMdir}${basename}_pp_surf)"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.flipTemplateFile.flipTemplateFile ${tdir}${flipTemplate})"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.subdivLevel.subdivLevel "<<GetSubdivLevel()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.spharmDegree.spharmDegree "<<GetSPHARMDegree()<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.regTemplateFile.regTemplateFile ${tdir}${regTemplate})"<<std::endl;
if (GetFinalFlipN()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<0<<")"<<std::endl;}
if (GetFinalFlipX()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<4<<")"<<std::endl;}
if (GetFinalFlipY()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<5<<")"<<std::endl;}
if (GetFinalFlipZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<7<<")"<<std::endl;}
if (GetFinalFlipXY()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<1<<")"<<std::endl;}
if (GetFinalFlipYZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<2<<")"<<std::endl;}
if (GetFinalFlipXZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<3<<")"<<std::endl;}
if (GetFinalFlipXYZ()==1){
BMSShapeAnalysisModuleFile<<"        SetAppOption(Para.finalFlipIndex.finalFlipIndex "<<6<<")"<<std::endl;}
 
if (GetParaOut1State()==true)
 {
BMSShapeAnalysisModuleFile<<"      SetAppOption(Para.writePara 1)"<<std::endl;
 }
BMSShapeAnalysisModuleFile<<"      Run(output ${Para} error)"<<std::endl;
BMSShapeAnalysisModuleFile<<"  if(${error} != '')"<<std::endl;
BMSShapeAnalysisModuleFile<<"    echo('ParaToSPHARMMesh: '${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    exit()"<<std::endl;
BMSShapeAnalysisModuleFile<<"  endif(${error})"<<std::endl;
BMSShapeAnalysisModuleFile<<"    endif(${value})"<<std::endl;

BMSShapeAnalysisModuleFile<<"EndForEach(${case})"<<std::endl;

BMSShapeAnalysisModuleFile<<"set(BMSdir '"<<GetOutputDirectory()<<"/BatchMake_Scripts')"<<std::endl;
BMSShapeAnalysisModuleFile<<" Set(BMSFile ${BMSdir}"<<"/ShapeAnalysisModule_MeanAsTemplate.bms"<<")"<<std::endl;
BMSShapeAnalysisModuleFile<<" CopyFile("<<GetBMSShapeAnalysisModuleFile()<<" ${BMSdir})"<<std::endl;
BMSShapeAnalysisModuleFile<<" DeleteFile("<<GetBMSShapeAnalysisModuleFile()<<")"<<std::endl;

}

//Overwrite (delete) the different files 
void ShapeAnalysisModuleComputation::OverWrite()
{
	int DataNumber=GetDataNumber();
	char **Base_Files; 
	Base_Files = new char *[DataNumber];
	

	for(int i=0;i<DataNumber;i++)
	{	
		Base_Files[i] = new char[512];
		std::strcpy(Base_Files[i],GetAllFilesName(i));
	}

	//Overwrite files created by SegPostProcess
	if( GetOverwriteSegPostProcess() )
	{
		char **PreProcessing_Files; 
		PreProcessing_Files = new char *[DataNumber];

	 	char *dir;
		dir=new  char[512] ;
		std::strcpy(dir, GetOutputDirectory());
		std::strcat(dir, "/Mesh/PostProcess/");

		for (int i = 0; i<DataNumber;i++)
		{
			PreProcessing_Files[i] = new char[512];  
			std::strcpy(PreProcessing_Files[i],dir);
			std::strcat(PreProcessing_Files[i],Base_Files[i]);
			std::strcat(PreProcessing_Files[i],"_pp.gipl.gz");
		}
		
		bool DirectoryEmpty=DirectoryIsEmpty(dir);
		if(!DirectoryEmpty)
		{
			cout<<"OverWrite SegPostProcess"<<endl;
			for (int k=0; k<DataNumber; k++)
			{	
				remove(PreProcessing_Files[k]);
				//cerr<<"Error deleting file "<<PreProcessing_Files[k]<<endl;
					
			}
		}
		else{ cerr<<"You have to compute SegPostProcess before overwriting!!"<<endl;}
	}
	
	//Overwrite files created by GenParaMesh
	if( GetOverwriteGenParaMesh() )
	{
		char **GenParaMesh_Files; 
		GenParaMesh_Files = new char *[2*DataNumber];

	 	char *dir;
		dir=new  char[512] ;
		std::strcpy(dir, GetOutputDirectory());
		std::strcat(dir, "/Mesh/SPHARM/");

		for (int i = 0; i<DataNumber;i++)
		{
			GenParaMesh_Files[i] = new char[512];  
			std::strcpy(GenParaMesh_Files[i],dir);
			std::strcat(GenParaMesh_Files[i],Base_Files[i]);
			std::strcat(GenParaMesh_Files[i],"_pp_para.vtk");

			GenParaMesh_Files[i+DataNumber] = new char[512];  
			std::strcpy(GenParaMesh_Files[i+DataNumber],dir);
			std::strcat(GenParaMesh_Files[i+DataNumber],Base_Files[i]);
			std::strcat(GenParaMesh_Files[i+DataNumber],"_pp_surf.vtk");
		}
		
		bool DirectoryEmpty=DirectoryIsEmpty(dir);
		if(!DirectoryEmpty)
		{
			cout<<"OverWrite GenParaMesh"<<endl;
			for (int k=0; k<2*DataNumber; k++)
			{
				remove(GenParaMesh_Files[k]);
				//cerr<<"Error deleting file "<<GenParaMesh_Files[k]<<endl;
			}
		}
		else{ cerr<<"You have to compute GenParaMesh before overwriting!!"<<endl;}
	}

	//Overwrite files created by ParaToSPHARMMesh
	if( GetOverwriteParaToSPHARMMesh() )
	{
		char **ParaToSPHARMMesh_Files; 
		ParaToSPHARMMesh_Files = new char *[7*DataNumber];

	 	char *dir;
		dir=new  char[512] ;
		std::strcpy(dir, GetOutputDirectory());
		std::strcat(dir, "/Mesh/SPHARM/");

		for (int i = 0; i<DataNumber;i++)
		{
			ParaToSPHARMMesh_Files[i] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i],dir);
			std::strcat(ParaToSPHARMMesh_Files[i],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i],"_pp_surfSPHARM.vtk");

			ParaToSPHARMMesh_Files[i+DataNumber] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i+DataNumber],dir);
			std::strcat(ParaToSPHARMMesh_Files[i+DataNumber],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i+DataNumber],"_pp_surfSPHARM_ellalign.vtk");

			ParaToSPHARMMesh_Files[i+2*DataNumber] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i+2*DataNumber],dir);
			std::strcat(ParaToSPHARMMesh_Files[i+2*DataNumber],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i+2*DataNumber],"_pp_surfSPHARM.coef");

			ParaToSPHARMMesh_Files[i+3*DataNumber] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i+3*DataNumber],dir);
			std::strcat(ParaToSPHARMMesh_Files[i+3*DataNumber],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i+3*DataNumber],"_pp_surfSPHARM_ellalign.coef");

			ParaToSPHARMMesh_Files[i+4*DataNumber] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i+4*DataNumber],dir);
			std::strcat(ParaToSPHARMMesh_Files[i+4*DataNumber],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i+4*DataNumber],"_pp_surfSPHARM_procalign.vtk");

			ParaToSPHARMMesh_Files[i+5*DataNumber] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i+5*DataNumber],dir);
			std::strcat(ParaToSPHARMMesh_Files[i+5*DataNumber],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i+5*DataNumber],"_pp_surf_paraPhi.txt");

			ParaToSPHARMMesh_Files[i+6*DataNumber] = new char[512];  
			std::strcpy(ParaToSPHARMMesh_Files[i+6*DataNumber],dir);
			std::strcat(ParaToSPHARMMesh_Files[i+6*DataNumber],Base_Files[i]);
			std::strcat(ParaToSPHARMMesh_Files[i+6*DataNumber],"_pp_surf_paraTheta.txt");

// 			ParaToSPHARMMesh_Files[i+7*DataNumber] = new char[512];  
// 			std::strcpy(ParaToSPHARMMesh_Files[i+7*DataNumber],dir);
// 			std::strcat(ParaToSPHARMMesh_Files[i+7*DataNumber],Base_Files[i]);
// 			std::strcat(ParaToSPHARMMesh_Files[i+7*DataNumber],"_pp_surf_tMeanSPHARM.vtk");
// 
// 			ParaToSPHARMMesh_Files[i+8*DataNumber] = new char[512];  
// 			std::strcpy(ParaToSPHARMMesh_Files[i+8*DataNumber],dir);
// 			std::strcat(ParaToSPHARMMesh_Files[i+8*DataNumber],Base_Files[i]);
// 			std::strcat(ParaToSPHARMMesh_Files[i+8*DataNumber],"_pp_surf_tMeanSPHARM_ellalign.vtk");
// 
// 			ParaToSPHARMMesh_Files[i+9*DataNumber] = new char[512];  
// 			std::strcpy(ParaToSPHARMMesh_Files[i+9*DataNumber],dir);
// 			std::strcat(ParaToSPHARMMesh_Files[i+9*DataNumber],Base_Files[i]);
// 			std::strcat(ParaToSPHARMMesh_Files[i+9*DataNumber],"_pp_surf_tMeanSPHARM.coef");

// 			ParaToSPHARMMesh_Files[i+10*DataNumber] = new char[512];  
// 			std::strcpy(ParaToSPHARMMesh_Files[i+10*DataNumber],dir);
// 			std::strcat(ParaToSPHARMMesh_Files[i+10*DataNumber],Base_Files[i]);
// 			std::strcat(ParaToSPHARMMesh_Files[i+10*DataNumber],"_pp_surf_tMeanSPHARM_ellalign.coef");
		
		}
		
		//check if the directory is empty
		bool DirectoryEmpty=DirectoryIsEmpty(dir);
		if(!DirectoryEmpty)
		{
			cout<<"OverWrite ParaToSPARHMMesh"<<endl;
			for (int k=0; k<7*DataNumber; k++)
			{
				remove(ParaToSPHARMMesh_Files[k]);
				//cerr<<"Error deleting file "<<ParaToSPHARMMesh_Files[k]<<endl;
			}
		}

		else{ cerr<<"You have to compute ParaToSPHARMMesh before overwriting!!"<<endl;}

		
		// Overwrite the template file;
		char *dirTemplate=NULL;
		dirTemplate=new  char[512] ;
		std::strcpy(dirTemplate, GetOutputDirectory());
		std::strcat(dirTemplate, "/Template/");

		bool templateDirectoryEmpty=DirectoryIsEmpty(dirTemplate);
		if(!templateDirectoryEmpty)
		{
			cout<<"OverWrite Templates"<<endl;
			int length=strlen(GetOutputDirectory());
			length=length+10;
	
			DIR *pdir = NULL;
			struct dirent *pent;
			pdir = opendir (dirTemplate);
			while ((pent=readdir(pdir)))
			{
				char *file=NULL;
				file= new char[512];
				strcpy(file,dirTemplate);
				strcat(file, pent->d_name);
				if(file[length]!='.')
				{	
					remove(file);
					//cerr<<"Error deleting file "<<file<<endl;
				}
			}
		}
	}
}

//Compute the mean of all the files
void ShapeAnalysisModuleComputation::ComputationMean()
{
	std::cout<<"Computing Mean"<<std::endl;
	int DataNumber=GetDataNumber();
	char **Base_Files; 
	Base_Files = new char *[DataNumber];

	int nbPoints=0;
	bool initialize=true;

	for(int i=0;i<DataNumber;i++)
	{	
		Base_Files[i] = new char[512];
		std::strcpy(Base_Files[i], GetOutputDirectory());
		std::strcat(Base_Files[i], "/Mesh/SPHARM/");
		std::strcat(Base_Files[i],GetAllFilesName(i));
		std::strcat(Base_Files[i],"_pp_surfSPHARM_procalign.vtk");

		//read a vtk file
		vtkPolyDataReader *meshin = vtkPolyDataReader::New();
		meshin->SetFileName(Base_Files[i]);
		
		try{
			meshin->Update();		
		}
		catch(...)
		{
			std::cout << "Cannot open file: " << Base_Files[i] << std::endl;
			return ;
		}
	
		vtkPolyData *poly= vtkPolyData::New();
		poly=meshin->GetOutput();
	
		//Get number of points
		vtkIdType idNumPointsInFile=poly->GetNumberOfPoints();
		nbPoints=idNumPointsInFile;

		vtkPoints * pts;
		pts=poly->GetPoints();
		
		// add all values of the coordinates
		if(initialize==true)
		{	
			for( int i = 0; i < nbPoints; i++)
			{	
				m_meanX.push_back(0);
				m_meanY.push_back(0);
				m_meanZ.push_back(0);
			}
			initialize=false;
		}

		for( int i = 0; i < nbPoints; i++)
   		{	
			double *p;
			p=pts->GetPoint(i);
		
			m_meanX[i]=m_meanX[i]+p[0];
 			m_meanY[i]=m_meanY[i]+p[1];
 			m_meanZ[i]=m_meanZ[i]+p[2];		
		}
	}

	for(int i = 0; i < nbPoints; i++)
   	{	
		m_meanX[i]=m_meanX[i]/DataNumber;
		m_meanY[i]=m_meanY[i]/DataNumber;
		m_meanZ[i]=m_meanZ[i]/DataNumber;	
	}

	WriteMeanFile(nbPoints);
	
}

//Write the mean file use as a template for ParaToSPHARMMesh
void ShapeAnalysisModuleComputation::WriteMeanFile(int nbPoints)
{
	char m_MeanFile[512];
	m_meanX.size();
	std::strcpy(m_MeanFile,GetOutputDirectory());
	std::strcat(m_MeanFile,"/Template/");
	std::strcat(m_MeanFile,"meanAll.vtk");

	cout<<m_MeanFile<<endl;

	std::ofstream meanAll(m_MeanFile);
	meanAll<<"# vtk DataFile Version 3.0"<<std::endl;
	meanAll<<"vtk output"<<std::endl;
	meanAll<<"ASCII"<<std::endl;
	meanAll<<"DATASET POLYDATA"<<std::endl;
	//meanAll<<"POINTS "<<nbPoints<<" float"<<std::endl;
	meanAll<<"POINTS "<<nbPoints<<" float"<<std::endl;

	for(unsigned int i=0;i<m_meanX.size();i+=3)
	{
		meanAll<<m_meanX[i]<<" "<<m_meanY[i]<<" "<<m_meanZ[i]<<" "<<m_meanX[i+1]<<" "<<m_meanY[i+1]<<" "<<m_meanZ[i+1]<<" "<<m_meanX[i+2]<<" "<<m_meanY[i+2]<<" "<<m_meanZ[i+2]<<endl;
	}
}



git-svn-id: https://www.nitrc.org/svn/spharm-pdm@6 026a22ec-4e7a-0410-994d-e47a0e92e701
#ifndef SHAPEANALYSISTOOLCOMPUTATION_H
#define SHAPEANALYSISTOOLCOMPUTATION_H

#include "Parameters.h"

#include <strstream> 
#include <iostream>
#include <cstring>
#include <fstream>
#include <stdio.h>
#include <itksys/Process.h>
#include <vector>

#include <string>
#include <stdlib.h>
#include <itksys/Glob.hxx>
#include <dirent.h>

#include "bmScriptParser.h"
#include "BMString.h"

class ShapeAnalysisModuleComputation: public Parameters
{
 public:
	
	ShapeAnalysisModuleComputation();
	~ShapeAnalysisModuleComputation();

	void SetBMSShapeAnalysisModuleFile(bool);
	char *GetBMSShapeAnalysisModuleFile();
	void SetBMSShapeAnalysisModuleFile2(bool);
	char *GetBMSShapeAnalysisModuleFile2();
	void SetBMSShapeAnalysisModuleMRMLFile(bool);
	char* GetBMSShapeAnalysisModuleMRMLFile();
	void SetOuputFile();
	char* GetOutputFile();
	void WriteBMSMRMLScene();
  	void WriteBMSShapeAnalysisModuleFile();
	void WriteBMSShapeAnalysisModuleFile2();
	void ExecuteBatchMake(char *_Input);  
  	void ExecuteMeshMath(int,char*);

	void Computation();
	void OverWrite();
	void ComputationMean();
	void WriteMeanFile(int);
  
	private:
  
	int m_StudyNumber;
	int ComputeMean;
    	char m_BMSShapeAnalysisModuleFile[512];
	char m_BMSShapeAnalysisModuleMRLMFile[512];
	char m_OutputFile[512];
	char m_SegPostProcessDir[512];
	char m_GenParaMeshDir[512];
	char m_ParaToSPHARMMeshDir[512];
	
	vector<int> m_Dims;
	vector<double>m_meanX;
	vector<double>m_meanY;
	vector<double>m_meanZ;	
};

#endif


git-svn-id: https://www.nitrc.org/svn/spharm-pdm@7 026a22ec-4e7a-0410-994d-e47a0e92e701
<?xml version="1.0" encoding="utf-8"?>
<executable>
	<category>
		UNC</category>
	<title> Shape Analysis Module</title>
	<description>
		Shape Analysis Module is a tool which allows the user to compute multiple subjects. It is using the SPHARM-PDM pipeline (SegPostProcess, GenParaMesh and ParaToSPHARMMesh). The input is a csv file containing all the information and one or more volume file. A csv file is a file used for the digital storage of data structured in a table of lists form, where each associated item (member) in a group is in association with others also separated by the commas of its set. The first line needs to contain the name of the different columns. The output is also a csv file and can be use with the shapeAnalysisMANCO tool. </description>
	<version>
		1.0</version>
	<documentation-url>http://www.nitrc.org/projects/spharm-pdm/</documentation-url>
	<license></license>
	<contributor>
		Corentin Hamel </contributor>
	<acknowledgements>
		This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. </acknowledgements>
	<parameters>
		<label>Group Project IO</label>
		<description>Input File and Output File</description>	
		<file>
			<name>GroupeProjectInputFile</name>
			<label>Input File</label>
			<index>1</index>
			<channel>input</channel>
			<default>None</default>
			<description>Input file</description>
		</file>
		
		<directory>
			<name>GroupeProjectOutputDirectory</name>
			<label>Output Directory</label>
			<index>2</index>
			<channel>output</channel>
			<default>None</default>
			<description>Output Directory</description>
		</directory>
		
	</parameters>
	<parameters>
		<label>Post Processed Segmentation</label>
		<description> SegPostProcess Main Parameters</description>
		<boolean>
			<name>OverwriteSegPostProcess</name>
			<label>Overwrite</label>
			<longflag>OverwriteSegPostProcess</longflag>
			<default>false</default>
			<description>Overwrite Post Processed Segmentation</description>
		</boolean>
		<float>
			<name>sx</name>
			<label>sx:</label>
			<longflag>sx</longflag> 
			<default>0.5</default>
			<constraints>
				<minimum>0</minimum>
				<maximum>1</maximum>
				<step>.1</step>
			</constraints>

		</float>
		
		<float>
			<name>sy</name>
			<label>sy:</label>
			<longflag>sy</longflag> 
			<default>0.5</default>
			<constraints>
				<minimum>0</minimum>
				<maximum>1</maximum>
				<step>.1</step>
			</constraints>
		</float>
		
		
		<float>
			<name>sz</name>
			<label>sz:</label>
			<longflag>sz</longflag> 
			<default>0.5</default>
			<constraints>
				<minimum>0</minimum>
				<maximum>1</maximum>
				<step>.1</step>
			</constraints>
		</float>
	
		<boolean>
			<name>LabelState</name>
			<label>Label Number</label> 
			<longflag>LabelState</longflag> 
			<default>false</default>-
		</boolean>
		
		<double>
			<name>ValueLabelNumber</name>
			<label>Value</label>
			<longflag>label</longflag> 
			<default>1</default>
			<constraints>
				<minimum>1</minimum>
				<maximum>100</maximum>
				<step>1</step>
			</constraints>
		</double>
	</parameters>
	
	
	<parameters>
			
		<label>Generate Mesh Parameters</label>
		<description>GenParaMesh Main Parameters</description>
		<boolean>
			<name>OverwriteGenParaMesh</name>
			<label>Overwrite</label>
			<longflag>OverwriteGenParaMesh</longflag>
			<default>false</default>
			<description>Overwrite Generate Mesh Parameters</description>
		</boolean>
		<integer>
			<name>NumberofIterations</name>
			<label>Number of Iterations</label>
			<longflag>NumberofIterations</longflag>
			<default>1000</default>
			<constraints>
				<minimum>1</minimum>
				<maximum>10000</maximum>
				<step>1</step>
			</constraints>
		</integer>
	</parameters>
		
	<parameters>
		
		<label>Parameters To SPHARM Mesh</label>
		<description>ParaToSPHARMMesh Main Parameters</description>
		<boolean>
			<name>OverwriteParaToSPHARMMesh</name>
			<label>Overwrite</label>
			<longflag>OverwriteParaToSPHARMMesh</longflag>
			<default>false</default>
			<description>Overwrite Parameters To SHARM Mesh</description>
		</boolean>
		<integer>
			<name>SubdivLevelValue</name>
			<label>SubdivLevel value</label>
			<longflag>SubdivLevelValue</longflag>
			<default>10</default>
			<constraints>
				<minimum>1</minimum>
				<maximum>100</maximum>
				<step>1</step>
			</constraints>
		</integer>
		
		<integer>
			<name>SPHARMDegreeValue</name>
			<label>SPHARM Degree value</label>
			<longflag>SPHARMDegreeValue</longflag>
			<default>15</default>
			<constraints>
				<minimum>1</minimum>
				<maximum>100</maximum>
				<step>1</step>
			</constraints>
		</integer>
		
		
	</parameters>	
	<parameters advanced="true">
		<label>Avanced Input File</label>
		<description>Choose the colum of the volume file</description>
		<boolean>
			<name>inputColumn</name>
			<label>Choose input volume column</label>
			<longflag>--inputColumn</longflag>
			<default>false</default>
			<description>able the user to choose the volume input file</description>
		</boolean>	
		<integer>
			<name>columVolumeFile</name>
			<label>Column number of volume input file</label>
			<longflag>--columVolumeFile</longflag>
			<default>0</default>
			<constraints>
				<minimum>1</minimum>
				<step>1</step>
			</constraints>
			<description>zero indexed</description>
		</integer>		
	</parameters>
	<parameters advanced="true">
		<label>Avanced Post Processed Segmentation</label>
		<description>SegPostProcess Advanced Parameters</description>
		
		<boolean>
			<name>GaussianFiltering</name>
			<label> Gaussian filtering</label>
			<longflag>GaussianFiltering</longflag>
			<default>false</default>
		</boolean>
		
		<integer>
			<name>VarianceX</name>
			<label>Variance of Gauss filter (x)</label>
			<longflag>varX</longflag>
			<default>10</default>
			<constraints>
				<minimum>10</minimum>
				<maximum>100</maximum>
				<step>1</step>
			</constraints>
		</integer>
	
		<integer>
			<name>VarianceY</name>
			<label>Variance of Gauss filter (y)</label>
			<longflag>varY</longflag>
			<default>10</default>
			<constraints>
				<minimum>10</minimum>
				<maximum>100</maximum>
				<step>1</step>
			</constraints>
		</integer>
		<integer>
			<name>VarianceZ</name>
			<label>Variance of Gauss filter (z)</label>
			<longflag>varZ</longflag>
			<default>10</default>
			<constraints>
				<minimum>10</minimum>
				<maximum>100</maximum>
				<step>1</step>
			</constraints>
		</integer>
					
		
	</parameters>	
	
	<parameters advanced="true">
		<label>Advanced Parameters to SPHARM Mesh</label>
		<description>Advanced Parameters to SPHARM Mesh</description>
			
		<boolean>
			<name>Template</name>
			<label>Use Flip/Reg Template</label>
			<longflag>Template</longflag>
			<default>false</default>
		</boolean>
		
		
		<file>
			<name>flipTemplate</name>
			<label>Flip Template (coef file)</label>
			<description>Flip Template (coef file)</description>
			<longflag>flipTemplate</longflag>
			<channel>input</channel>
			<default>None</default>
		</file>

		<file>
			<name>regTemplate</name>
			<label>Reg Template (mesh file)</label>
			<description>Reg Template (mesh file)</description>
			<longflag>regTemplate</longflag>
			<channel>input</channel>
			<default>None</default>
		</file>
		
		<boolean>SetParameterFile
			<name>MTemplate</name>
			<label>Use Mean as the Template</label>
			<longflag>MTemplate</longflag>
			<default>false</default>
		</boolean>
		
		<boolean>
			<name>ParaOut1Template</name>
			<label>ParaOut (template)</label>
			<longflag>paraOutTemplate</longflag>
			<default>true</default>
		</boolean>

		<boolean>
			<name>NoFLip</name>
			<label>No Flip</label>
			<longflag>noFlip</longflag>
			<default>true</default>
		</boolean>
			
		<boolean>
			<name>FlipALongAxisX</name>
			<label>Flip Along Axis of x</label>
			<longflag>FlipALongAxisX</longflag>
			<default>false</default>
		</boolean>
			
		<boolean>
			<name>FlipALongAxisY</name>
			<label>Flip Along Axis of y</label>
			<longflag>FlipALongAxisY</longflag>
			<default>false</default>
		</boolean>
		
		<boolean>
			<name>FlipALongAxisZ</name>
			<label>Flip Along Axis of z</label>
			<longflag>FlipALongAxisZ</longflag>
			<default>false</default>
		</boolean>
		
		<boolean>
			<name>FlipALongAxisXandY</name>
			<label>Flip Along Axis of x and y</label>
			<longflag>FlipALongAxisXandY</longflag>
			<default>false</default>
		</boolean>
		
		<boolean>
			<name>FlipALongAxisYandZ</name>
			<label>Flip Along Axis of y and z</label>
			<longflag>FlipALongAxisYandZ</longflag>
			<default>false</default>
		</boolean>
		
		<boolean>
			<name>FlipALongAxisXandZ</name>
			<label>Flip Along Axis of x and z</label>
			<longflag>FlipALongAxisXandZ</longflag>
			<default>false</default>
		</boolean>
		
		<boolean>
			<name>FlipALongAxisXandYandZ</name>
			<label>Flip Along Axis of x and y and z</label>
			<longflag>FlipALongAxisXandYandZ</longflag>
			<default>false</default>
		</boolean>-->
		
	</parameters>
	


</executable>

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@8 026a22ec-4e7a-0410-994d-e47a0e92e701
Making a new dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@9 026a22ec-4e7a-0410-994d-e47a0e92e701
deleting dir MeshMath

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@10 026a22ec-4e7a-0410-994d-e47a0e92e701
making a new dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@11 026a22ec-4e7a-0410-994d-e47a0e92e701
deleting dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@12 026a22ec-4e7a-0410-994d-e47a0e92e701
creating dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@13 026a22ec-4e7a-0410-994d-e47a0e92e701
<BatchMakeApplicationWrapper>
	<BatchMakeApplicationWrapperVersion>1.0</BatchMakeApplicationWrapperVersion>
	<Module>
		<Name>SegPostProcessCLP</Name>
		<Version>1.0</Version>
		<Path>SegPostProcessCLP</Path>
		<Parameters>
			<Param>
				<Type>4</Type>
				<Name>fileName</Name>
				<Value></Value>
				<Parent>0</Parent>
				<External>1</External>
				<Optional>0</Optional>
			</Param>
			<Param>
				<Type>4</Type>
				<Name>outfileName</Name>
				<Parent>0</Parent>
				<Value></Value>
				<External>0</External>
				<Optional>0</Optional>
			</Param>
			<Param>
				<Type>1</Type>
				<Name>gaussianOn</Name>
				<Parent>0</Parent>
				<Value>--Gauss</Value>
				<External>0</External>
				<Optional>1</Optional>
			</Param>
			<Param>
				<Type>1</Type>
				<Name>variance_vect</Name>
				<Value>--var</Value>
				<Parent>0</Parent>
				<External>0</External>
				<Optional>1</Optional>
			</Param>
			<Param>
				<Type>4</Type>
				<Name>variance_vect.variance_vect</Name>
				<Value></Value>
				<Parent>1</Parent>
				<External>0</External>
				<Optional>0</Optional>
			
			</Param>
			<Param>
				<Type>1</Type>
				<Name>label</Name>
				<Value>--label</Value>
				<Parent>0</Parent>
				<External>0</External>
				<Optional>1</Optional>
			</Param>
			<Param>
				<Type>2</Type>
				<Name>label.label</Name>
				<Value></Value>
				<Parent>2</Parent>
				<External>0</External>
				<Optional>0</Optional>
			</Param>
			
			<Param>
				<Type>1</Type>
				<Name>spacing_vect</Name>
				<Value>--space</Value>
				<Parent>0</Parent>
				<External>0</External>
				<Optional>1</Optional>
			</Param>
			<Param>
				<Type>4</Type>
				<Name>spacing_vect.spacing_vect</Name>
				<Value></Value>
				<Parent>3</Parent>
				<External>0</External>
				<Optional>0</Optional>
			
			</Param>
		</Parameters>
	</Module>
</BatchMakeApplicationWrapper>


git-svn-id: https://www.nitrc.org/svn/spharm-pdm@14 026a22ec-4e7a-0410-994d-e47a0e92e701
creating new dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@15 026a22ec-4e7a-0410-994d-e47a0e92e701
deleting dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@16 026a22ec-4e7a-0410-994d-e47a0e92e701
creating new dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@17 026a22ec-4e7a-0410-994d-e47a0e92e701
/* 
 * author:  msturm, mstyner 
 * created: 16 Apr 1997
 * changes: 1998, 1999, 2002
 *
 * contains routines for command line parsing 
 * (mostly adapted from gaudi toolbox, changed to templated functions)
 *
 */

#ifndef __ARGIO_H__
#define __ARGIO_H__

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>



const int ipMAXTOKLEN = 255; // max. length of a token

// some workarounds for template function
typedef char* charp;

inline float fatof(const char *str) {
  return (float) atof(str);
}

// command line parsing

template <class T>
inline T ipGetArgument(const char **argv, const char *keystr, 
                 T (*convert) (const char *str), const T defval) {
  for (int i=1; argv[i]; i++)
    if (strstr(argv[i],keystr))
      if (argv[i+1]) return convert(argv[i+1]);
      else {
     fprintf(stderr,"Error: ipGetArgument: argument value of option \"%s\" is missing!\n", 
          argv[i]);

     exit(-1);
      }

  return defval;
}

inline charp ipGetStringArgument(const char **argv, const char *keystr, const charp defval)
{
  char *_defval = (defval ? strdup(defval): NULL);
  //return ipGetArgument(argv, keystr, strdup, _defval);
  for (int i=1; argv[i]; i++)
    if (strstr(argv[i],keystr))
      if (argv[i+1]) return strdup(argv[i+1]);
      else {
     fprintf(stderr,"Error: ipGetArgument: argument value of option \"%s\" is missing!\n", 
          argv[i]);

     exit(-1);
      }

  return _defval;
}

// reads in multiple string arguments started by keystr and ended by an '-' or
// end of args
inline int ipGetStringMultipArgument(const char **argv, const char *keystr, char **out, const int max) {
  int i = 1, num;
  while (argv[i]) {
    if (strstr(argv[i],keystr)) {
      // keystr found
      if (argv[i+1] && (argv[i+1])[0] != '-') {
        i++;
        num = 0;
        out[0] = strdup(argv[i]);
        i++; num++;
        while (argv[i] && num < max && (argv[i])[0] != '-') {
          out[num] = strdup(argv[i]);
          i++;num++; }
        return num;
        // jump back !
      } else {
        fprintf(stderr,"Error: ipGetArgument: argument value of option \"%s\" is missing!\n", argv[i]);
        exit(-1); } } // if keystr
    i++; } //while
  return 0;}


inline int ipGetIntArgument(const char **argv, const char *keystr, const int defval) {
  //return ipGetArgument(argv, keystr, atoi, defval);{
  for (int i=1; argv[i]; i++)
    if (strstr(argv[i],keystr))
      if (argv[i+1]) return atoi(argv[i+1]);
      else {
     fprintf(stderr,"Error: ipGetArgument: argument value of option \"%s\" is missing!\n", 
          argv[i]);

     exit(-1);
      }

  return defval;
}

inline float ipGetFloatArgument(const char **argv, const char *keystr, const float defval) {
  //return ipGetArgument(argv, keystr, fatof, defval);
  for (int i=1; argv[i]; i++)
    if (strstr(argv[i],keystr))
      if (argv[i+1]) return fatof(argv[i+1]);
      else {
     fprintf(stderr,"Error: ipGetArgument: argument value of option \"%s\" is missing!\n", 
          argv[i]);

     exit(-1);
      }

  return defval;
}

inline double ipGetDoubleArgument(const char **argv, const char *keystr, const double defval) {
  //return ipGetArgument(argv, keystr, atof, defval);
  for (int i=1; argv[i]; i++)
    if (strstr(argv[i],keystr))
      if (argv[i+1]) return atof(argv[i+1]);
      else {
     fprintf(stderr,"Error: ipGetArgument: argument value of option \"%s\" is missing!\n", 
          argv[i]);

     exit(-1);
      }

  return defval;
}

inline int ipExistsArgument(const char **argv, const char *keystr) {
  for (int i=1; argv[i]; i++) 
    if (strstr(argv[i],keystr)) return 1;
  
  return 0;
}


// string utilities
// appends src to resized dst and returns it
inline char *ipAppendString(char *&dst, const char *src){
  if (dst) {
    dst = (char *) realloc(dst, strlen(dst) + strlen(src) + 1);
    return strcat(dst, src);  }
  else return strdup(src);}

     
/*************************************************************
 * counts the words on one line 
 ************************************************************/ 
inline int ipLineWordCount(const char *s){
    int n = 0;
    for (;;) {
        while (isspace(*s)) s++;
        if (*s == '\0') return n;
        while (isgraph(*s)) s++;
        n++;    }}


/*************************************************************
 * gets the generic name of a file cutting the extension 
 ************************************************************/ 
inline char *ipGetBaseName(const char *string){
  int i;
  char *ret = NULL, *retp = NULL; 
  if (!(ret = strdup(string))) {
    fprintf(stderr, "Error: ipGetBaseName [%s, line %d]: strdup() failed:",
            __FILE__, __LINE__);
    perror("");
    exit(errno);  }  
  for(i=0, retp=ret; i<strlen(string);i++, retp++)
    if (*retp == '.') {
      *retp = '\0';
      break;    } 
  return ret;}

     
/*************************************************************
 * reads a line into s (already allocated) and returns length
 * lim describes the max line length.
 * function proposed by Kernighan and Ritchie
 ************************************************************/ 
inline int ipfgetline(FILE* f, char* s, int lim){
    int   c,i;
    for(i=0; (i<lim-1) && ((c=getc(f))!=EOF) && (c!='\n'); ++i)
        s[i]=c;
    if (c=='\n'){
        s[i]=c;
        ++i;
    }
    s[i]='\0';
    return(i);}           

// extracts string tokens from a string which are either separeted by 
//    - white-space (isspace()) or 
//    - punctuation (ispunct()) except '.', '+', '-', '_'
// and converts them to type <class T>.
//
// at most n tokens will be extracted, tokenval[] has to be
// allocated
// returns number of tokens found, converted tokens in tokenval[]

template <class T>
int ipExtractTokens(T *tokenval, const char *tokenstr, const int n,
              T (*convert) (const char *str)) {
  char *tmp_token = new char [ipMAXTOKLEN];
  char *tmp_tokenp = tmp_token;
  const char *tokenp = tokenstr;
  int  i = 0;

  while ((i < n) && (*tokenp)) {
    memset(tmp_token, '\0', ipMAXTOKLEN * sizeof(char));
    while (isspace(*tokenp) && *tokenp) tokenp++;
    tmp_tokenp = tmp_token;
    while ((*tokenp) && (isalnum(*tokenp) || (*tokenp == '.') || 
                (*tokenp == '-') || (*tokenp == '+') || 
                (*tokenp == '_') ) && 
        ((tmp_tokenp - tmp_token) < ipMAXTOKLEN)) 
      *(tmp_tokenp++) = *(tokenp++);
    if(*tokenp) tokenp++; // skip separator
    tokenval[i++] = convert(tmp_token);
  }
  
  delete [] tmp_token;

  return i;
}

// extracts string tokens from a string which are either separeted by 
//    - white-space (isspace()) or
//    - commas
// and converts them to type <class T>.
//
// at most n tokens will be extracted, tokenval[] has to be
// allocated
// returns number of tokens found, converted tokens in tokenval[]

template <class T>
int ipExtractSpaceSepTokens(T *tokenval, const char *tokenstr, const int n,
                   T (*convert) (const char *str)) {
  char *tmp_token = new char [ipMAXTOKLEN];
  char *tmp_tokenp = tmp_token;
  const char *tokenp = tokenstr;
  int  i = 0;

  while ((i < n) && (*tokenp)) {
    memset(tmp_token, '\0', ipMAXTOKLEN * sizeof(char));
    while (isspace(*tokenp) && *tokenp) tokenp++;
    tmp_tokenp = tmp_token;
    while ((*tokenp) && (isspace(*tokenp) || (*tokenp != ',') ) && 
        ((tmp_tokenp - tmp_token) < ipMAXTOKLEN)) 
      *(tmp_tokenp++) = *(tokenp++);
    if(*tokenp) tokenp++; // skip separator
    tokenval[i++] = convert(tmp_token);
  }
  
  delete [] tmp_token;

  return i;
}


inline int ipExtractIntTokens(int *tokenval, const char *tokenstr, const int n) {
  //  return ipExtractTokens(tokenval, tokenstr, n, atoi);
  char *tmp_token = new char [ipMAXTOKLEN];
  char *tmp_tokenp = tmp_token;
  const char *tokenp = tokenstr;
  int  i = 0;

  while ((i < n) && (*tokenp)) {
    memset(tmp_token, '\0', ipMAXTOKLEN * sizeof(char));
    while (isspace(*tokenp) && *tokenp) tokenp++;
    tmp_tokenp = tmp_token;
    while ((*tokenp) && (isalnum(*tokenp) || (*tokenp == '.') || 
                (*tokenp == '-') || (*tokenp == '+') || 
                (*tokenp == '_') ) && 
        ((tmp_tokenp - tmp_token) < ipMAXTOKLEN)) 
      *(tmp_tokenp++) = *(tokenp++);
    if(*tokenp) tokenp++; // skip separator
    tokenval[i++] = atoi(tmp_token);
  }
  
  delete [] tmp_token;

  return i;
}

inline int ipExtractFloatTokens(float *tokenval, const char *tokenstr, const int n) {
  //  return ipExtractTokens(tokenval, tokenstr, n, fatof);
  char *tmp_token = new char [ipMAXTOKLEN];
  char *tmp_tokenp = tmp_token;
  const char *tokenp = tokenstr;
  int  i = 0;

  while ((i < n) && (*tokenp)) {
    memset(tmp_token, '\0', ipMAXTOKLEN * sizeof(char));
    while (isspace(*tokenp) && *tokenp) tokenp++;
    tmp_tokenp = tmp_token;
    while ((*tokenp) && (isalnum(*tokenp) || (*tokenp == '.') || 
                (*tokenp == '-') || (*tokenp == '+') || 
                (*tokenp == '_') ) && 
        ((tmp_tokenp - tmp_token) < ipMAXTOKLEN)) 
      *(tmp_tokenp++) = *(tokenp++);
    if(*tokenp) tokenp++; // skip separator
    tokenval[i++] = fatof(tmp_token);
  }
  
  delete [] tmp_token;

  return i;
}

inline int ipExtractDoubleTokens(double *tokenval, const char *tokenstr, const int n) {
  // return ipExtractTokens(tokenval, tokenstr, n, atof);
  char *tmp_token = new char [ipMAXTOKLEN];
  char *tmp_tokenp = tmp_token;
  const char *tokenp = tokenstr;
  int  i = 0;

  while ((i < n) && (*tokenp)) {
    memset(tmp_token, '\0', ipMAXTOKLEN * sizeof(char));
    while (isspace(*tokenp) && *tokenp) tokenp++;
    tmp_tokenp = tmp_token;
    while ((*tokenp) && (isalnum(*tokenp) || (*tokenp == '.') || 
                (*tokenp == '-') || (*tokenp == '+') || 
                (*tokenp == '_') ) && 
        ((tmp_tokenp - tmp_token) < ipMAXTOKLEN)) 
      *(tmp_tokenp++) = *(tokenp++);
    if(*tokenp) tokenp++; // skip separator
    tokenval[i++] = atof(tmp_token);
  }
  
  delete [] tmp_token;

  return i;
}

inline int ipExtractStringTokens(char **tokenval, const char *tokenstr, const int n) {
  // return ipExtractSpaceSepTokens(tokenval, tokenstr, n, strdup);
  char *tmp_token = new char [ipMAXTOKLEN];
  char *tmp_tokenp = tmp_token;
  const char *tokenp = tokenstr;
  int  i = 0;

  while ((i < n) && (*tokenp)) {
    memset(tmp_token, '\0', ipMAXTOKLEN * sizeof(char));
    while (isspace(*tokenp) && *tokenp) tokenp++;
    tmp_tokenp = tmp_token;
    while ((*tokenp) && (isalnum(*tokenp) || (*tokenp == '.') || 
                (*tokenp == '-') || (*tokenp == '+') || 
                (*tokenp == '_') ) && 
        ((tmp_tokenp - tmp_token) < ipMAXTOKLEN)) 
      *(tmp_tokenp++) = *(tokenp++);
    if(*tokenp) tokenp++; // skip separator
    tokenval[i++] = strdup(tmp_token);
  }
  
  delete [] tmp_token;

  return i;
}

#endif


git-svn-id: https://www.nitrc.org/svn/spharm-pdm@18 026a22ec-4e7a-0410-994d-e47a0e92e701
new dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@19 026a22ec-4e7a-0410-994d-e47a0e92e701
new dir

git-svn-id: https://www.nitrc.org/svn/spharm-pdm@20 026a22ec-4e7a-0410-994d-e47a0e92e701