/**
 *  GraphTFT plugin for the Video Disk Recorder 
 * 
 *  common.c - A plugin for the Video Disk Recorder
 *
 *  (c) 2004 Lars Tegeler, Sascha Volkenandt 
 *
 * This code is distributed under the terms and conditions of the
 * GNU GENERAL PUBLIC LICENSE. See the file COPYING for details.
 *
 * $Id: common.c,v 1.3 2004/05/25 08:41:15 tegeler Exp $
 *
 **/

//includes
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <syslog.h>
#include "common.h"
#include "setup.h"

//file exists 
#include <sys/stat.h>

//use std::string
using std::string;

//for debuging
#ifdef DEBUG
void d(int level, const char *fmt, ...)
{
  auto char    t[BUFSIZ];
  auto va_list ap;
  auto time_t  now;
  FILE* lf = NULL;

  va_start(ap, fmt);

  if (GraphTFTSetup.Level >= level)
    switch (GraphTFTSetup.Logger) {
      case STDOUT : vsnprintf(t + 21, sizeof t - 21, fmt, ap);
                    time(&now);
                    strftime(t, sizeof t, "[graphTFT: %H:%M:%S]", localtime(&now));
                    t[20] = ' ';
                    printf("%s\033[K", t);
                    break;

      case SYSLOG : vsnprintf(t + 10, sizeof t - 10, fmt, ap);
                    memcpy(t, "[graphTFT] ", 10);
                    syslog(LOG_DEBUG, "%s", t);
                    break;

      case ASFILE : if (lf == (FILE *)NULL)
                      lf = fopen("/tmp/graphTFT.log", "a");
                    if (lf != (FILE *)NULL) {
                      vsnprintf(t + 20, sizeof t - 20, fmt, ap);
                      time(&now);
                      strftime(t, sizeof t, "%d.%m.%Y %H:%M:%S", localtime(&now));
                      t[19] = ' ';
                      fprintf(lf, "%s\n", t);
                    }
                    break;
    }

  va_end(ap);
}
#endif

//check if a file exists
bool file_exists(std::string filename) {
	struct stat file_stat;
	return ((stat(filename.c_str(), &file_stat) == 0) ? true:false);
}

//FIX ME: grrr, why somebody must habe an conversion, some must not, and by some it wont work at all
int  
isolat1ToUTF8(unsigned char* out, int *outlen, const unsigned char* in, int *inlen) {
	unsigned char* outstart = out;
	const unsigned char* base = in;
	unsigned char* outend = out + *outlen;
	const unsigned char* inend;
	const unsigned char* instop;
	unsigned int c = *in;

	inend = in + (*inlen);
	instop = inend;
					    
	while (in < inend && out < outend - 1) {
	if (c >= 0x80) {
	*out++= ((c >>  6) & 0x1F) | 0xC0;
	*out++= (c & 0x3F) | 0x80;
	++in;
	c = *in;
	}
	if (instop - in > outend - out) instop = in + (outend - out); 
	while (c < 0x80 && in < instop) {
	*out++ =  c;
	++in;
	c = *in;
	}
	}	
	if (in < inend && out < outend && c < 0x80) {
	*out++ =  c;
	++in;
	}
	*outlen = out - outstart;
	*inlen = in - base;
	return(0);
}

