/*
    ham callsign functions
    Copyright (C) 2011 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 <zcall.h>
#include <zstr.h>

#include <ctype.h>
#include <string.h>



char *z_get_raw_call(char *buf, const char *call){
    char s[20], *c;
    char *token_ptr;

    z_strlcpy(s, call, 20);
   
    for (c = strtok_r(s, "/", &token_ptr); 
         c!=NULL; 
         c = strtok_r(NULL, "/", &token_ptr)){ 
        if (strlen(c) < 3) continue;
        if (strlen(c) == 3 && c[2] >= '0' && c[2] <= '9') continue;
          /*  3rd char cannot be number , OK1 vs G8M */
        z_strlcpy(buf, c, 20);  
        return buf;
    }
    z_strlcpy(buf, call, 20);
    z_str_uc(buf);
    return buf;
}

int z_call_is_rover(const char *callsign){
    int len = strlen(callsign);
    if (len < 2) return 0;
    if (callsign[len - 2] != '/') return 0;
    if (z_char_uc(callsign[len - 1]) != 'R') return 0;
    return 1;
}

char *z_suffix(gchar *call){
    char *needle;

	if (!call) return NULL;

    for (needle=call+strlen(call)-1; 
         needle>=call && isalpha(*needle); 
         needle--); 

    return needle+1;
}

int z_can_be_call_char(const char c, int flags){
	if (c >= 'a' && c <= 'z') return 1;
	if (c >= 'A' && c <= 'Z') return 1;
	if (c >= '0' && c <= '9') return 1;
	if (ZCBC_SLASH && c == '/') return 1;
	if (ZCBC_MINUS && c == '-') return 1;
	return 0;
}

int z_can_be_call(const char *call, int flags){
	const char *c;
	int a = 0, n = 0, m = 0;

	for (c = call; *c != '\0'; c++){
		if (*c >= 'a' && *c <= 'z') { a++ ; continue; }
		if (*c >= 'A' && *c <= 'Z') { a++ ; continue; }
		if (*c >= '0' && *c <= '9') { n++ ; continue; }
		if (ZCBC_SLASH && *c == '/') continue;
		if (ZCBC_MINUS && *c == '-') { m++ ; continue; }
		return 0;
	}
	if (a < 2) return 0; // at least two alphas, also empty string
	if (n < 1) return 0; // must have a number
	if (n > 5) return 0; // maximum is like 9A2000X
	if (m == 0){	// not for OK2M-3 from KST
		char ch = z_char_uc(call[strlen(call) - 1]);
		if ((ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9')) return 0;  // doesn't end with letter
	}
	return 1;

}
