// Computes specificity of the model by comparing random samples of the model with the test mashes.
float specificity(Logger& logger, StatisticalModelType::Pointer model, const MeshDataList& testMeshes, unsigned numberOfSamples) {


	// draw a number of samples and compute its distance to the closest training dataset
    double accumulatedDistToClosestTrainingShape = 0;
    for (unsigned i = 0; i < numberOfSamples; i++) {
        MeshType::Pointer sample = model->DrawSample();

        double minDist = std::numeric_limits<double>::max();
        for (MeshDataList::const_iterator it = testMeshes.begin(); it != testMeshes.end(); ++it) {
            MeshType::Pointer testMesh = it->first;

            // before we compute the distances between the meshes, we normalize the scale by scaling them
            // to optimally match the mean. This makes sure that models that include scale and those that have them normalized
            // ar etreated the same.
             MeshType::Pointer sampledScaledToMean = normalizeScale(sample, model->DrawMean());
             MeshType::Pointer testScaledToMean = normalizeScale(testMesh, model->DrawMean());

             double dist = computeAverageDistance(testScaledToMean, sampledScaledToMean, ConfigParameters::numSamplingPointsSpecificity);
            logger.Get(logINFO) << "distance " << dist << std::endl;
            if (dist < minDist) {
                minDist = dist;
            }
        }
        logger.Get(logINFO) << "closest distance for sample " << i << ": " << minDist << std::endl;

        accumulatedDistToClosestTrainingShape += minDist;
    }
    double avgDist = accumulatedDistToClosestTrainingShape / numberOfSamples;
    logger.Get(logINFO) << "average distance " << avgDist << std::endl;
    return avgDist;
}
void buildImageIntensityModelOnROI(const char* referenceFilename, const char* maskFilename, const char* dir, const char* outputImageFilename) {


	typedef itk::PCAModelBuilder<RepresenterType> ModelBuilderType;
	typedef itk::StatisticalModel<RepresenterType> StatisticalModelType;
    typedef std::vector<std::string> StringVectorType;
    typedef itk::DataManager<RepresenterType> DataManagerType;

    RepresenterType::Pointer representer = RepresenterType::New();

	typedef itk::ImageFileReader< ImageType > MaskReaderType;
	MaskReaderType::Pointer maskReader = MaskReaderType::New();
	maskReader->SetFileName( maskFilename );
    maskReader->Update();

	representer->SetReference( ReadImageFromFile(referenceFilename), maskReader->GetOutput() );

    StringVectorType filenames;
    getdir(dir, filenames, ".vtk");

    DataManagerType::Pointer dataManager = DataManagerType::New();
	dataManager->SetRepresenter(representer);

    for (StringVectorType::const_iterator it = filenames.begin(); it != filenames.end(); it++) {
        std::string fullpath = (std::string(dir) + "/") + *it;

        dataManager->AddDataset( ReadImageFromFile(fullpath), fullpath.c_str());
    }

	ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New();
    StatisticalModelType::Pointer model = pcaModelBuilder->BuildNewModel(dataManager->GetSampleDataStructure(), 0);

    std::cout<<"dimensionality of the data: "<<model->GetDomain().GetNumberOfPoints()<<", dimension of the images: "<<(*dataManager->GetSampleDataStructure().begin())->GetSample()->GetLargestPossibleRegion().GetNumberOfPixels()<<std::endl;

    std::cout<<"writing the mean sample to a png file..."<<std::endl;
    
	typedef itk::ImageFileWriter< ImageType > ImageWriterType;
	ImageWriterType::Pointer writer = ImageWriterType::New();
	writer->SetFileName( outputImageFilename );
	writer->SetInput(model->DrawSample());
    writer->Update();

}