//-----------------------------------------------------------------------------

#pragma once

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

//-----------------------------------------------------------------------------

namespace graphene
{
namespace utility
{

//-----------------------------------------------------------------------------

struct Landmark_guidance
{
    std::vector<std::string> filenames;
};

//-----------------------------------------------------------------------------

static bool read_landmark_guidance(const std::string& filename,
                                   const std::string& folder,
                                   Landmark_guidance& landmark_guidance,
                                   size_t n_landmarks)
{
    // Open file
    std::ifstream ifs(filename);
    if (!ifs)
    {
        printf("[ERROR] Cannot open %s for reading landmark guidance\n",
               filename.c_str());
        return false;
    }

    // Parse
    std::string line;

    int start_index;
    int end_index;
    std::string fn_help_image;

    while (std::getline(ifs, line))
    {
        std::stringstream linestream(line);

        if (line.empty())
            continue;

        // line is not empty, check if it is commented out
        if (line[0] == '#')
            continue;

        linestream >> start_index >> end_index >> fn_help_image;

        if (linestream.fail())
        {
            printf("[ERROR] While parsing line %s\n", line.c_str());
            printf("[ERROR] Expecting format: start end filename\n");
            return false;
        }

        int num_landmarks_for_image = end_index - start_index + 1;

        if (end_index - start_index < 0)
        {
            printf("[ERROR] While parsing range: start < end\n");
            printf("[ERROR]   In line: %s\n", line.c_str());
            return false;
        }

        for (int i = 0; i < num_landmarks_for_image; ++i)
        {
            landmark_guidance.filenames.push_back(folder + "/" + fn_help_image);
        }
    }

    // Sanity Check
    if (landmark_guidance.filenames.size() != n_landmarks)
    {
        printf("[ERROR] Parsed only %lu landmark images from %s, need %lu\n",
               landmark_guidance.filenames.size(),
               filename.c_str(),
               n_landmarks);

        return false;
    }

    return true;
}

//-----------------------------------------------------------------------------

}
}

//-----------------------------------------------------------------------------
