/***************************************************************************
**
**  This file is part of QGpCoreTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2012-02-08
**  Copyright: 2012-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#ifndef FLETCHERCHECKSUM_H
#define FLETCHERCHECKSUM_H

#include "QGpCoreToolsDLLExport.h"

namespace QGpCoreTools {

  class QGPCORETOOLS_EXPORT FletcherChecksum
  {
  public:
    FletcherChecksum() {_values.a=0; _values.b=0;}
    FletcherChecksum(unsigned char a, unsigned char b) {_values.a=a; _values.b=b;}
    FletcherChecksum(const FletcherChecksum& o) {_raw=o._raw;}

    bool operator==(const FletcherChecksum& o) const {return _raw==o._raw;}

    void reset() {_values.a=0; _values.b=0;}
    inline void add(const char * buffer, int length);

    unsigned char a() const {return _values.a;}
    unsigned char b() const {return _values.b;}
  private:
    union {
      struct {
        unsigned char a, b;
      } _values;
      unsigned char _bytes[2];
      unsigned short _raw;
    };
  };

  inline void FletcherChecksum::add(const char * buffer, int length)
  {
    for(int i=0; i<length; i++) {
      _values.a+=buffer[i];
      _values.b+=_values.a;
    }
  }

} // namespace QGpCoreTools

#endif // FLETCHERCHECKSUM_H
