/*
 * (C) Copyright 2005- ECMWF.
 *
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
 * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
 */

#undef NDEBUG
#include <assert.h>
#include <cstdio>
#include "eccodes.h"

const unsigned char bufrEdition0[] = {
    0x42, 0x55, 0x46, 0x52, 0x00, 0x00, 0x12, 0x00, 0x00, 0x62, 0x01, 0x80, 0x00, 0x01, 0x00, 0x00, 0x58, 0x09, 0x02, 0x17,
    0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x01, 0x01, 0x7c, 0x49, 0x0a, 0xe0, 0x00, 0x42, 0x9f, 0xaa, 0x00, 0x60, 0x3e, 0xac,
    0x00, 0x30, 0x38, 0x34, 0x39, 0x35, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0xc2,
    0x0a, 0xe0, 0x00, 0x0a, 0xe0, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x01,
    0x80, 0xc7, 0x05, 0x0d, 0x17, 0x0d, 0x0d, 0xbe, 0x31, 0x41, 0x31, 0x1f, 0xc0, 0x3f, 0xbf, 0x41, 0x1d, 0x3f, 0xc0, 0x00,
    0x00, 0x00, 0x5a, 0x00, 0x10, 0xf7, 0xaf, 0x89, 0x21, 0x5c, 0x06, 0x03, 0xea, 0xc2, 0x14, 0xfd, 0x50, 0x06, 0x57, 0xff,
    0xf9, 0xe5, 0xbf, 0xff, 0x7d, 0x01, 0xe5, 0xc2, 0x59, 0x97, 0xf5, 0xdc, 0x01, 0x08, 0x80, 0xff, 0xff, 0xff, 0xde, 0xf9,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x0b, 0x08,
    0x18, 0x77, 0x77, 0xff, 0xe3, 0x46, 0x8d, 0x1a, 0x34, 0x68, 0xd1, 0xa3, 0x46, 0x8d, 0x1a, 0x34, 0x6a, 0x13, 0x67, 0xd5,
    0x8d, 0x1a, 0xac, 0x6a, 0x55, 0x2a, 0x46, 0x8d, 0x1a, 0x30, 0x37, 0x37, 0x37, 0x37
};

int main(int argc, char* argv[])
{
    size_t totalLength = 194;
    codes_handle* h = codes_handle_new_from_message(0, bufrEdition0, totalLength);
    assert(h);
    CODES_CHECK(codes_set_long(h, "unpack", 1), "Failed to decode");

    const int dump_flags = GRIB_DUMP_FLAG_CODED | GRIB_DUMP_FLAG_OCTET | GRIB_DUMP_FLAG_VALUES | GRIB_DUMP_FLAG_READ_ONLY;
    grib_dump_content(h, stdout, "bufr_simple", dump_flags, NULL);
    codes_handle_delete(h);

    // Use the fast header extractor
    const char* outfile = "temp_bufr_edition0.bin";
    FILE* out = fopen(outfile, "wb");
    if (!out) return 1;
    if (fwrite(bufrEdition0, 1, totalLength, out) != totalLength) {
        perror(argv[1]);
        return 1;
    }
    fclose(out);

    int num_messages = 0;
    codes_bufr_header* header_array = NULL;
    const int strict_mode = 1;
    int err = codes_bufr_extract_headers_malloc(0, outfile, &header_array, &num_messages, strict_mode);
    if (err) return err;
    assert(header_array->edition == 0);
    assert(header_array->bufrHeaderCentre == 98);
    assert(header_array->typicalYear == 1988);
    free(header_array);

    return 0;
}
