#include <ImageDev/ImageDev.h>
#include <ioformat/IOFormat.h>
#include <string.h>

using namespace imagedev;
using namespace ioformat;
using namespace iolink;

int
main( int argc, char* argv[] )
{
    int status = 0;

    try
    {
        // ImageDev library initialization
        if ( isInitialized() == false )
            imagedev::init();

        // Open a binary image from a vip file
        auto imageInput = readVipImage( std::string( IMAGEDEVDATA_IMAGES_FOLDER ) + "polystyrene_sep.vip" );

        // Connected component labeling of the binary image
        std::cout << "Labeling the binary input..." << std::endl;
        auto imageLab = labeling2d( imageInput, Labeling2d::LABEL_8_BIT, Labeling2d::CONNECTIVITY_8 );

        // Define the analysis features to be computed
        std::cout << "Performing the label analysis..." << std::endl;
        AnalysisMsr::Ptr analysis = std::make_shared< AnalysisMsr >();
        auto diameter = analysis->select( NativeMeasurements::equivalentDiameter );
        auto feretRatio = analysis->select( NativeMeasurements::feretRatio2d );

        // Launch the feature extraction on the segmented image
        labelAnalysis( imageLab, imageInput, analysis );
        size_t labelCount = analysis->labelCount();
        std::cout << "  - Number of objects = " << labelCount << std::endl;
        // Print the 4 first results of the analysis
        std::cout << "Label\t" << diameter->name() << "\t" << feretRatio->name() << std::endl;
        for ( int i = 0; i < 4; i++ )
        {
            std::cout << ( i + 1 ) << "\t" << diameter->value( i ) << "\t\t\t" << feretRatio->value( i ) << std::endl;
        }

        std::cout << "This example ran successfully." << std::endl;
    }
    catch ( const imagedev::Exception& error )
    {
        // Print potential exception in the standard output
        std::cerr << "ImageDev exception: " << error.what() << std::endl;
        status = -1;
    }

    // ImageDev library finalization
    imagedev::finish();

    // Check if we must ask for an enter key to close the program
    if ( !( ( argc == 2 ) && strcmp( argv[1], "--no-stop-at-end" ) == 0 ) )
        std::cout << "Press Enter key to close this window." << std::endl, getchar();

    return status;
}
