#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include "vars.h"

 int load_cache(char ***list,int *count, char *cache_name)
  {
   char etmp[ML_ETMP],*k;
   int i,size;
   void *mem;
   FILE *fp;

   #ifdef DEBUG_LOAD_CACHE
   fprintf(stderr,"READ cache from %s\n",cache_name);
   #endif
   
   // File exist?
   if (access(cache_name,F_OK))
      {
       *count=0;
       return(1);
      }
  
   // Open file
   if ((fp=fopen(cache_name,"rb"))==NULL)
     { // Open error
       sprintf(etmp,"ERROR: Can't open file, exit: %s: %s",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }

  // Determine file size
  if (fseek(fp, 0, SEEK_END))
     { // Seek error
       sprintf(etmp,"ERROR: Can't seek file %s\n",cache_name);
       err_mes(etmp);
       exit(-1);
     }
     
    size=ftell(fp);
   #ifdef DEBUG_LOAD_CACHE
   fprintf(stderr," file size=%i\n",size);
   #endif
 
  // Seek to ban_urls_count
  if (fseek(fp, sizeof(time_t), SEEK_SET))
     { // Seek error
       sprintf(etmp,"ERROR: Can't seek file %s\n",cache_name);
       err_mes(etmp);
       exit(-1);
     }

  // Allocate memory
     mem=malloc(size);
     if (mem==NULL)
       {
        sprintf(etmp,"ERROR: Can't allocate memory. Exit.\n");
        err_mes(etmp);
        exit(-1);
       }

  // read data to memory
    if (fread(mem,size-sizeof(time_t),1,fp)<1)
     { // Read error
       sprintf(etmp,"ERROR: Can't read from file %s: %s\n",cache_name,strerror(errno));
       err_mes(etmp);
       exit(-1);
     }

     fclose(fp);

 // SET ban_urls_count
   *count=((int*)mem)[0];

   #ifdef DEBUG_LOAD_CACHE
    fprintf(stderr," element count=%i\n",*count);
   #endif

   // set pointer to pointer table
    *list=(char **)(mem+sizeof(int));

   // Calc first string
   k=(char *)(mem+sizeof(int)+(*count)*sizeof(char*));
   
 // Set pointers table;
    for (i=0;i<*count;i++)
    {
    (*list)[i]= (long int)(*list)[i]+k;
//     (*list)[i]= (*list)[i]+k;
    }

  #ifdef DEBUG_LOAD_CACHE
   fprintf(stderr,"=== CACHE LOADED ===\n");
   // print urls
   for(i=0;i<*count;i++)
    fprintf(stderr,"%s\n",(*list)[i]);
  #endif

  sprintf(etmp,"Load %i rules from %s",*count,cache_name);
  err_mes(etmp);

 return(0);
}

