/***********************************************************************
*
*               Module   : StrDict
*               Fichier  : StrDictFile.c
*               Auteur   : J. DUCLOY
*               Date     : Novembre 2013 from StrSearchGet
*
************************************************************************/

#include "StrDict.h"
#include "CharSet.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Buffer.h"

static Buffer* buf=NULL;

StrDict *StrDictAddFromFile (StrDict *table, char*stream)
{
  char *buffer;  
  FILE *fichier;
  char *posTab;
  char *key;
  char *value;
  int len;

  if(!buf)buf=BufferCreate(100,50);

  if((fichier = fopen(stream, "r")))
    {
      while ((buffer=BufferFgets(buf,fichier)))
	{
	  if((posTab=strchr(buffer,'\t')))
	    {
	      len = posTab-buffer;
	      key=malloc(len+1);
	      strncpy(key, buffer, len); key[len]='\0';
	      len = strlen(buffer);
	      if(buffer[len-1]=='\n')buffer[len-1]='\0';
	      value=malloc(strlen(posTab)+1);
	      strcpy(value,posTab+1);
	      StrDictSet(table,key,value);
	    }
	  else 
	    {
	      StrDictSet(table,BufferSave(buf),"");
	    }
	};
      return (table);
    }
  else return NULL;
}

StrDict *StrDictFromFile (char *stream)
{
  StrDict *dict;
  dict=NewStrDict();
  if (StrDictAddFromFile (dict, stream)) return dict;
  return NULL;
}

StrDict *StrDictFromVarPath (char *var, char *path)
{
  static Buffer *bufName=NULL;
  StrDict *dict;
  char *base;
  if (!bufName) bufName=NewBuffer();
  base=getenv(var);
  if (base)
    {
      dict=NewStrDict();
      BufferStrcpy(bufName, base);
      BufferStrcat(bufName, "/");
      BufferStrcat(bufName, path);
      if (StrDictAddFromFile (dict, BufferString(bufName))) return dict;
    }
  return NULL;
}
