/*
   axgetmail
   (c) 1999 by Radek Burget OK2JBG

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version
   2 of the license, or (at your option) any later version.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include "common.h"

int msg_level = MSG_RESULT;

void message(int level, const char *fmt, ...)
{
  va_list argptr;

  if (level >= msg_level)
  {
    va_start(argptr, fmt);
    /*if (level == MSG_ERROR) vfprintf(stderr, fmt, argptr);
                       else vfprintf(stdout, fmt, argptr);*/
    vfprintf(stdout, fmt, argptr);
    va_end(argptr);
  }
}

int call_ssid(const char *src)
{
  char *p = (char *)(src);
  while (*p != '\0' && *p != '-') p++;
  if (*p) p++;
  if (*p) return atoi(p);
     else return 0;
}

char *call_call(const char *src)
{
  static char s[15];
  char *p = (char *)(src);
  strcpy(s, "");
  while (*p && isalnum(*p) && strlen(s) < 6) {strncat(s, p, 1); p++;}
  return s;
}

char *strip_ssid(char *src)
{
  if (call_ssid(src) == 0)
  {
    char *p = src;
    while (*p != '\0' && *p != '-') p++;
    *p = '\0';
  }
  return src;
}

char *normalize_call(char *call)
{
  char c[8];
  int ssid;
  char *p;

  strcpy(c, call_call(call));
  ssid = call_ssid(call);
  if (ssid == 0) strcpy(call, c); else sprintf(call, "%s-%i", c, ssid);
  for (p = call; *p; p++) *p = toupper(*p);
  return call;
}

/* Compare callsign only (not the SSID) */
int compare_call(char *call1, char *call2)
{
  char c1[15];
  char c2[15];
  strcpy(c1, call_call(call1));
  strcpy(c2, call_call(call2));
  return (strcasecmp(c1, c2) == 0);
}

/* wait for the character and read it */
int ffgetc(FILE *f)
{
  int ch;
  do
  {
    ch = fgetc(f);
  } while (ch == -1 && (errno == EAGAIN || errno == EINTR));
  if (ch == -1)
  {
    message(MSG_ERROR, "Connection failure\n");
    exit(RET_ERR);
  }
  return ch;
}

int is_empty(char *line)
{
  char *p = line;

  while (*p)
  {
    if (!isspace(*p)) return 0;
    else p++;
  }
  return 1;
}

