#include <Elementary.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "file_utils.h"
#include "Ecrire.h"

static char *
_buf_append(char *buf, const char *str, int *len, int *alloc)
{
   int len2 = strlen(str);
   if ((*len + len2) >= *alloc)
     {
        char *buf2 = realloc(buf, *alloc + len2 + 512);
        if (!buf2) return NULL;
        buf = buf2;
        *alloc += (512 + len2);
     }
   strcpy(buf + *len, str);
   *len += len2;
   return buf;
}

char *
file_load(const char *file)
{
   FILE *f;
   size_t size;
   struct stat st;
   int alloc = 0, len = 0;
   char *text = NULL, buf[16384 + 1];

   if (stat(file, &st) != -1)
     {
        if (st.st_size == 0) return strdup("");
     }

   f = fopen(file, "rb");
   if (!f) return NULL;

   while ((size = fread(buf, 1, sizeof(buf) - 1, f)))
     {
        char *tmp_text;
        buf[size] = 0;
        tmp_text = _buf_append(text, buf, &len, &alloc);
        if (!tmp_text) break;
        text = tmp_text;
     }
   fclose(f);
   return text;
}

char *
file_plain_load(const char *file)
{
   char *text;

   text = file_load(file);
   if (text)
     {
        char *text2;

        text2 = elm_entry_utf8_to_markup(text);
        free(text);
        return text2;
     }
   return NULL;
}

Eina_Bool
file_save(const char *file, const char *text)
{
   FILE *f;
   struct stat st;

   if (stat(file, &st) != -1)
     {
        if (S_ISDIR(st.st_mode))
          return EINA_FALSE;
     }

   f = fopen(file, "wb");
   if (!f)
     return EINA_FALSE;

   if (text)
     {
        if (fputs(text, f) == EOF)
          {
             ERR("Error in writing to '%s'.", file);
             return EINA_FALSE;
          } 
     }
   fclose(f);
   return EINA_TRUE;
}

Eina_Bool
file_plain_save(const char *file, const char *text)
{
   char *text2;
   Eina_Bool ok;

   text2 = elm_entry_markup_to_utf8(text);
   if (!text2)
     return EINA_FALSE;
   ok = file_save(file, text2);
   free(text2);

   return ok;
}


