/***************************** 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 *************************************/

#ifndef MVBINARYREADER_H
#define MVBINARYREADER_H

#include <string>
#include <vector>

#include <stdio.h>
#include <string.h>

//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();

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

private:
    char* data_;
    char* dataStart_;
    int recordMarker_;
    std::streampos size_;

public:
    template <typename T>
    T read()
    {
        T v;
        size_t s = sizeof(v);
        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);
        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);
        memcpy((char*)&vArray, data_, num * s);
        data_ += num * s;
        vArray[num] = '\0';
        str             = std::string(vArray);
    }
};

#endif  // MVBINARYREADER_H
