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

#include <stdio.h>
#include <gdbm.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
/* #include <getopt.h> some machines need*/
#include "station.h"

void usage(char* name)
{
    fprintf(stderr, "usage: %s -l|-n|-i ", name);
    exit(1);
}

int main(int argc, char** argv)
{
    char* defbase;
    FILE* f;
    GDBM_FILE db;
    datum key;
    datum content;
    int n, i, c, z;
    char buf[1024], tmp_buf[1024];
    station st;
    position pos;
    extern char* optarg;
    extern int optind, opterr;
    char mode = 0;
    int errflg = 0, counter = 0;
    char* p;
    char base[1024];
    char last_char = 'X';
    int blocksize = 0; /* less than 512 forces the system default */
    while ((c = getopt(argc, argv, "l:n:i:")) != -1)
        switch (c) {
            case 'l':
            case 'n':
            case 'i':
                mode = c;
                defbase = optarg;
                break;

            case '?':
                errflg++;
            default:
                break;
        }

    if (errflg)
        usage(argv[0]);
    if (mode == 0)
        usage(argv[0]);

    sprintf(base, "%s-%c.db", defbase, mode);

    db = gdbm_open(base, blocksize, GDBM_NEWDB, 0777, 0); /* last arg is pointer to callback fn */

    if (!db) {
        perror("dbm_open");
        exit(1);
    }


    /* write database with a key to search with. */

    while (fgets(buf, sizeof(buf), stdin) != 0) {
        buf[strcspn(buf, "\n")] = '\0'; /* remove trailing newline character */
        /* Read the last field as 1023c as it may contain whitespace. */
        memset(tmp_buf, '\0', 1024);
        sscanf(buf, "%d %li %li %d %d %d %s %1023c",
               &st.ident, &st.pos.lat, &st.pos.lon,
               &st.barometre_height, &st.pos.station_height,
               &st.pressure_level,
               st.pos.flags, tmp_buf);

        /* Eat multiple whitespace to make the name look OK. */
        p = tmp_buf;
        counter = 0;

        while (*p) {
            if (last_char == ' ' && *p == ' ') {
                p++;
                continue;
            }
            else {
                st.name[counter] = *p;
                last_char = *p;
                p++;
                counter++;
            }
        }
        st.name[counter] = '\0';


        switch (mode) {
            case 'i':
                key.dptr = (char*)&st.ident;
                key.dsize = sizeof(st.ident);
                break;
            case 'l':
                key.dptr = (char*)&st.pos;
                key.dsize = sizeof(st.pos);
                break;
            case 'n':
                key.dptr = (char*)&st.name;
                key.dsize = strlen(st.name) + 1;
                break;
            default:
                break;
        }

        content.dptr = (char*)&st;
        content.dsize = sizeof(st) - sizeof(st.name) + strlen(st.name) + 1;

        gdbm_store(db, key, content, GDBM_INSERT);
    }

    gdbm_close(db);
    exit(0);
}
