#include "Stdafx.h"
#include "MLHelpers.h"

namespace MLHelpers
{
  FILE* m_f=0;
  int   m_iNestingLevel=0;
  
  int InitRead(FILE* f)
  {
    m_f=f;
    return (0);
  }

  int InitWrite(FILE* f)
  {
    m_f=f;
    return (0);
  }

  int Shutdown    ()
  {
    m_f=0;
    return (0);
  }

  
  int NestingLevel()
  {
    return (m_iNestingLevel);
  }

  void WriteTabs(int iTabs)
  { 
    int i;
    for (i=0 ; i<iTabs ; i++)
    {
      fprintf(m_f, "\t");
    }

  }

  int IsCorrect(const char* pcString)
  {
    const char* pcIterator;

    for (pcIterator=pcString ; *pcIterator ; pcIterator++)
    {
      if (*pcIterator=='<' ||
          *pcIterator=='>' ||
          *pcIterator=='/' )
      {
        return (0);
      }      
    }

    return (1);
  }

  int WriteTag(int iTabs, const char* pcTagName, bool bOpen)
  {
    if (!IsCorrect(pcTagName))
    {
      return (false);
    }

    WriteTabs(iTabs+(bOpen?0:-1));
    
    if (fprintf(m_f, bOpen?"<%s>\n":"</%s>\n", pcTagName)<0)
    {
      return (-1);
    }

    bOpen?m_iNestingLevel++:m_iNestingLevel--;
    
    return (0);
  }

  int __cdecl WriteRaw(int iTabs, const char* pcFormat , ...)
  {
    char pcOutput[4096];

    WriteTabs(iTabs);

    va_list lst;	
	  va_start (lst, pcFormat);
	  vsprintf( pcOutput, pcFormat, lst);
	  va_end (lst);

    if (fprintf(m_f, "%s", pcOutput)<0)
    {
      return (-1);
    }

    return (0);
  }
}