/*
 * © Copyright 1996-2012 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.
 */

#include "mars.h"

typedef struct data {
    char* file;
    int one;
    int archive;
} data;

static data setup;

static option opts[] = {
    {
        NULL,
        "BUFRTOREQUEST_FILE",
        "-f",
        NULL,
        t_str,
        sizeof(char*),
        OFFSET(data, file),
    },
    {
        NULL,
        "BUFRTOREQUEST_ONE",
        "-1",
        "0",
        t_boolean,
        sizeof(boolean),
        OFFSET(data, one),
    },
    {
        NULL,
        "BUFRTOREQUEST_ARCHIVE",
        "-1",
        "0",
        t_boolean,
        sizeof(boolean),
        OFFSET(data, archive),
    },
};

int main(int argc, char** argv) {
    FILE* fd     = 0;
    int e        = 0;
    int cnt      = 0;
    long buflen  = 1024 * 1024 * 20;
    long length  = buflen;
    char* buffer = reserve_mem(length);
    request* a   = empty_request("BUFR");
    request* g   = empty_request("BUFR");
    char buf[80];
    long64 size, here, total;
    request *r;

    marsinit(&argc, argv, &setup, NUMBER(opts), opts);
    if (!setup.file) {
        printf("Usage: %s -1 -f <file>\n", argv[0]);
        printf("          -1 : print a single request\n");
        printf("          -f : file to process\n");
        marsexit(1);
    }


    start_timer();
    if ((fd = fopen(setup.file, "r")) == NULL) {
        marslog(LOG_EROR | LOG_PERR, "fopen: %s", setup.file);
        marsexit(1);
    }

    fseek(fd, 0, SEEK_END);
    total = ftell(fd);
    fseek(fd, 0, SEEK_SET);

    r = request_from_stream(fd, &size);


    here = ftell(fd);
    if(here + size !=total) {
        marslog(LOG_EXIT, "Size mistmatch %lld != %lld", here + size ,total);
    }

    unset_value(r, "YEAR");
    unset_value(r, "MONTH");
    unset_value(r, "FOREWARD");

    print_all_requests(r);


    fclose(fd);

    marsexit(e);
}
