// Reads a FIT file with the FIT C++ SDK, as an application does: the
// integrity check, then the decode with a listener. Built under
// AddressSanitizer by prove.sh, it shows where the SDK reads past its own
// buffers on a damaged file.
#include <fstream>
#include <iostream>

#include "fit_decode.hpp"
#include "fit_mesg_broadcaster.hpp"

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        std::cerr << "usage: repro <file.fit>\n";
        return 2;
    }
    std::ifstream file(argv[1], std::ios::in | std::ios::binary);
    if (!file)
    {
        std::cerr << "could not open " << argv[1] << "\n";
        return 2;
    }
    fit::Decode decode;
    const bool intact = decode.CheckIntegrity(file);
    std::cout << "CheckIntegrity: " << (intact ? "passed" : "failed") << "\n";
    if (intact)
    {
        file.clear();
        file.seekg(0, std::ios::beg);
        fit::MesgBroadcaster broadcaster;
        try
        {
            decode.Read(file, broadcaster);
            std::cout << "Read: done\n";
        }
        catch (const fit::RuntimeException& e)
        {
            std::cout << "Read: " << e.what() << "\n";
        }
    }
    return 0;
}
