#include "CommPrinter.h"

#include <string.h>
#include <stdio.h>
#include <stdarg.h>

static CommPrinter* g_pCommPrinterInstance = NULL;

CommPrinter* CommPrinter_Construct(CommPrinter* pThis)
{
  pThis->nDummy = 0;

  return pThis;
}

void CommPrinter_Destruct(CommPrinter* pThis)
{
  if(pThis)
  {
    free(pThis);
  }

  g_pCommPrinterInstance = NULL;
}

CommPrinter* CommPrinter_Instance(void)
{
  if(g_pCommPrinterInstance)
  {
  }
  else
  {
    g_pCommPrinterInstance = CommPrinter_Construct((CommPrinter*)malloc(sizeof(CommPrinter)));
  }

  return g_pCommPrinterInstance;
}

void CommPrinter_Reverse(CommPrinter* pThis, char s[])
{
  char    c;
  size_t  i;
  size_t  j;

  for(i = 0, j = strlen(s) - 1; i < j; i++, j--)
  {
    c    = s[i];
    s[i] = s[j];
    s[j] = c;
  }
}

void CommPrinter_Itoa(CommPrinter* pThis, int n, char s[])
{
  int i;
  int sign;

  if((sign = n) < 0) 
  {
    n = -n;
  }

  i = 0;
  do
  {
   s[i++] = n % 10 + '0';
  } while((n /= 10) > 0);

  if(sign < 0) 
  {
    s[i++] = '-';
  }
  s[i] = 0;

  CommPrinter_Reverse(pThis, s);
}

int CommPrinter_Mefprint(CommPrinter* pThis, int nId, char *fmt ...)
{
   char fname[200];
   char sId  [ 10];
  
   va_list  argpoint;
   FILE     *file = NULL;
 
   strcpy(fname, "./Error/SLog_");
   sprintf(sId, "%04d", nId);
   strcat(fname, sId);
   strcat(fname, ".txt");
 
   if((file = fopen(fname, "a")))
   {
     va_start(argpoint, fmt);
     vfprintf(file, fmt, argpoint);
     fflush(file);
     fclose(file);
     va_end(argpoint);
   }
   else
   {
     printf("! ERROR Unable to open mefprint file <%s>\n", fname);
     fflush(stdout);
   }

   return 0;
}
