#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/sysinfo.h>
#include <sys/soundcard.h>
#undef MIN
#undef MAX
#include "helpfunc.h"

void d(int level, const char *fmt, ...)
  {
  auto char    t[BUFSIZ];
  auto va_list ap;
  auto time_t  now;
  va_start(ap, fmt);
  if (ptvsetup.debug >= level)
    switch (ptvsetup.logger)
      {
      case STDOUT : time(&now);
      	   	    vsnprintf(t + 9, sizeof t - 9, fmt, ap);
                    strftime(t, sizeof t, "%H:%M:%S", localtime(&now));
                    t[8] = ' ';
                    if (ptvsetup.linuxver == 6)
                      {
                      printf("\r%s\033[K\r\n", t);
                      fflush(stdout);
                      }
                    else
                      printf("%s\033[K\n", t);
                    break;
      case SYSLOG : vsnprintf(t + 10, sizeof t - 10, fmt, ap);
                    memcpy(t, "PTV_: ", 10);
                    syslog(LOG_DEBUG, "%s", t);
                    break;
      }
  va_end(ap);
  }

char *Freq2Channelname (int frequency) 
  {
  int select;
  static char channelname[64];
  select = frequency / 1000;
  switch (select)
    {
    case 48 ... 62:
       sprintf(channelname, "K0%d",  (select - 34)/7);
       break;
    case 69 ... 83:
       sprintf(channelname, "S0%d",  (select - 62)/7);
       break;
    case 105 ... 168:
       sprintf(channelname, "SE%d",  (select - 98)/7);
       break;
    case 175 ... 224:
       sprintf(channelname, "K%d", (select - 140)/7);
       break;
    case 231 ... 294:
       sprintf(channelname, "SE%d",  (select - 154)/7);
       break;
    case 303 ... 463:
       sprintf(channelname, "S%d",  (select - 135)/8);
       break;
    case 471 ... 855:
       sprintf(channelname, "K%d",   (select - 303)/8);
       break;
    default:
       sprintf(channelname, "non-PAL frequency");
    }
  return channelname;
  }

