/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include <stdio.h>

#include <cstring>

#include <string>
#include <vector>

// This class is meant to read binary files. It is mainly used to
// decode the binary output generated by flexpart.

class MvBinaryReader
{
public:
    MvBinaryReader(const std::string&);
    ~MvBinaryReader();
    MvBinaryReader(const MvBinaryReader&) = delete;
    MvBinaryReader& operator=(const MvBinaryReader&) = delete;

    bool isValid() const;
    void skipRecMarker();
    void skip(size_t n) { data_ += n; }
    bool hasData() const;

private:
    char* data_{nullptr};
    char* dataStart_{nullptr};
    int recordMarker_{4};
    std::streampos size_{0};

public:
    template <typename T>
    T read()
    {
        T v;
        size_t s = sizeof(v);
        std::memcpy((void*)&v, data_, s);
        data_ += s;
        return v;
    }

    template <typename T>
    void read(int num, std::vector<T>& vec)
    {
        T vArray[num];
        T v;
        size_t s = sizeof(v);
        std::memcpy((void*)&vArray, data_, num * s);
        data_ += num * s;
        vec = std::vector<T>(vArray, vArray + num);
    }

    void read(int num, std::string& str)
    {
        char vArray[num + 1];
        char v;
        size_t s = sizeof(v);
        std::memcpy((char*)&vArray, data_, num * s);
        data_ += num * s;
        vArray[num] = '\0';
        str = std::string(vArray);
    }
};
