/*
    Tucnak - VHF contest log
    Copyright (C) 2002-2022  Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include "header.h"

#include "cwdb.h"
#include "mmm.h"
#include "fifo.h"
#include "language2.h"
#include "main.h"
#include "namedb.h"

int load_mmm_from_file(struct cw *cw, struct namedb *namedb, char *filename, int *nlocs, int *nnames){
    FILE *f;
    int ret=0;
	char *c;
	
    f=fopen(filename, "rt");
    if (!f) {
        log_addf(VTEXT(T_CANT_OPEN_S), filename);
        return -1;
    }

	GString *gs = g_string_sized_new(200);
	GString *dummy = g_string_sized_new(20);
	GString *call = g_string_sized_new(20);
	GString *wwl = g_string_sized_new(20);
	GString *name = g_string_sized_new(20);

	while ((c = zfile_fgets(gs, f, 0)) != NULL){
		g_string_assign(gs, c);
		if (gs->len > 2 && gs->str[0] == '/' && gs->str[1] == '/') continue;
			
		z_strtok_csv_simple(gs, call);
		z_strtok_csv_simple(gs, dummy);
		z_strtok_csv_simple(gs, wwl);
		z_strtok_csv_simple(gs, dummy);
		z_strtok_csv_simple(gs, dummy);
		z_strtok_csv_simple(gs, dummy);
		z_strtok_csv_simple(gs, dummy);
		z_strtok_csv_simple(gs, name);


		if (wwl->len == 6){
			if (!find_wwl_by_call(cw, call->str)){  /*only unknown calls, we don't know which is newer*/
				add_cw(cw, call->str, wwl->str, 19700101, NULL);
				add_wc(cw, wwl->str, call->str, 19700101);
				(*nlocs)++;
			}
		}

		if (namedb && name->len >= 2){
			add_namedb(namedb, call->str, name->str);
			(*nnames)++;
		}

	}

	g_string_free(gs, TRUE);
	g_string_free(dummy, TRUE);
	g_string_free(call, TRUE);
	g_string_free(wwl, TRUE);
	g_string_free(name, TRUE);

    ret=0;
    fclose(f);
    return ret;
}

