]> git.ipfire.org Git - thirdparty/sarg.git/blobdiff - log.c
Add an option to make sarg generates the css template
[thirdparty/sarg.git] / log.c
diff --git a/log.c b/log.c
index 94eedddd6331f5b02a3e8327089194ce6ccc988d..344fc3b1e268c5f6d3a530d07cc3775a4b175ada 100644 (file)
--- a/log.c
+++ b/log.c
 #include "include/conf.h"
 #include "include/defs.h"
 
+#ifdef HAVE_GETOPT_H
+#include <getopt.h>
+#endif
+
 #define REPORT_EVERY_X_LINES 5000
 #define MAX_OPEN_USER_FILES 10
 
@@ -37,7 +41,7 @@ struct userfilestruct
    FILE *file;
 };
 
-static char *userfile=NULL;
+/*@null@*/static char *userfile=NULL;
 
 numlist weekdays = { { 0, 1, 2, 3, 4, 5, 6 }, 7 };
 numlist hours = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
@@ -84,7 +88,6 @@ int main(int argc,char *argv[])
    char wuser[MAXLEN];
    char smartfilter[MAXLEN];
    char dia[128];
-   char wdata[128];
    char mes[30];
    char ano[30];
    char hora[30];
@@ -99,7 +102,6 @@ int main(int argc,char *argv[])
    char hexclude[MAXLEN];
    char csort[MAXLEN];
    int cstatus;
-   char tbuf[128];
    char tbuf2[128];
    char zip[20];
    char *str;
@@ -121,44 +123,70 @@ int main(int argc,char *argv[])
    int  x;
    int  errflg=0;
    int  puser=0;
-   int  fhost=0;
-   int  dns=0;
-   int  fuser=0;
+   bool  fhost=false;
+   bool  dns=false;
+   bool  fuser=false;
    int  idata=0;
    int  mindate=0;
+   int  maxdate=0;
    int  iarq=0;
-   int  exstring=0;
    int isa_ncols=0,isa_cols[ISACOL_Last];
-   int from_stdin;
+   bool from_stdin;
+   bool from_pipe;
    int blen;
    int maxopenfiles;
    int nopen;
-   int id_is_ip;
+   bool id_is_ip;
    long totregsl=0;
    long totregsg=0;
    long totregsx=0;
-   long totper=0;
+   bool totper=false;
    long int max_elapsed=0;
-   time_t tt;
+   long long int iyear, imonth, iday;
+   bool realt;
+   bool userip;
+   struct tm tt;
    struct tm *t;
    unsigned long recs1=0UL;
    unsigned long recs2=0UL;
    int OutputNonZero = REPORT_EVERY_X_LINES ;
-   int download_flag=0;
+   bool download_flag=false;
    char *download_url=NULL;
    struct getwordstruct gwarea;
-   struct longlinestruct line;
+   longline line;
+   time_t tnum;
+   struct stat logstat;
    struct userinfostruct *uinfo;
    struct userfilestruct *first_user_file, *ufile, *ufile1, *prev_ufile;
+   static int split=0;
+   static int convert=0;
+   static int output_css=0;
+   int option_index;
+   static struct option long_options[]=
+   {
+      {"convert",no_argument,&convert,1},
+      {"css",no_argument,&output_css,1},
+      {"split",no_argument,&split,1},
+      {0,0,0,0}
+   };
 
 #ifdef HAVE_LOCALE_H
    setlocale(LC_TIME,"");
 #endif
 
 #if defined(ENABLE_NLS) && defined(HAVE_LOCALE_H)
-   setlocale (LC_ALL, "");
-   bindtextdomain (PACKAGE_NAME, LOCALEDIR);
-   textdomain (PACKAGE_NAME);
+   if (!setlocale (LC_ALL, "")) {
+      fprintf(stderr,"SARG: Cannot set the locale LC_ALL to the environment variable\n");
+      exit(EXIT_FAILURE);
+   }
+   if (!bindtextdomain (PACKAGE_NAME, LOCALEDIR)) {
+      fprintf(stderr,"SARG: Cannot bind to text domain %s in directory %s (%s)\n",PACKAGE_NAME,LOCALEDIR,strerror(errno));
+      exit(EXIT_FAILURE);
+   }
+   if (!textdomain (PACKAGE_NAME)) {
+      fprintf(stderr,"SARG: Cannot set gettext domain for %s PACKAGE_NAME (%s)\n",PACKAGE_NAME,strerror(errno));
+      exit(EXIT_FAILURE);
+   }
 #endif //ENABLE_NLS
 
    BgImage[0]='\0';
@@ -176,8 +204,8 @@ int main(int argc,char *argv[])
    UserTabFile[0]='\0';
    BlockIt[0]='\0';
    ExternalCSSFile[0]='\0';
-   SquidGuardLogFormat[0]='\0';
-   SquidGuardLogAlternate[0]='\0';
+   RedirectorLogFormat[0]='\0';
+   NRedirectorLogs=0;
    for (ilf=0 ; ilf<ILF_Last ; ilf++) ilf_count[ilf]=0;
 
    sprintf(ExcludeCodes,"%s/exclude_codes",SYSCONFDIR);
@@ -195,10 +223,10 @@ int main(int argc,char *argv[])
    strcpy(FontSize,"9px");
    strcpy(TempDir,"/tmp");
    strcpy(OutputDir,"/var/www/html/squid-reports");
-   Ip2Name=0;
+   Ip2Name=false;
    strcpy(DateFormat,"u");
-   OverwriteReport=0;
-   RemoveTempFiles=1;
+   OverwriteReport=false;
+   RemoveTempFiles=true;
    strcpy(ReplaceIndex,"index.html");
    Index=INDEX_YES;
    RecordsWithoutUser=RECORDWITHOUTUSER_IP;
@@ -215,12 +243,12 @@ int main(int argc,char *argv[])
    strcpy(TopsitesSortType,"D");
    LongUrl=0;
    strcpy(FontFace,"Verdana,Tahoma,Arial");
-   strcpy(datetimeby,"elap");
+   datetimeby=DATETIME_BYTE;
    strcpy(CharSet,"ISO-8859-1");
    Privacy=0;
    strcpy(PrivacyString,"***.***.***.***");
    strcpy(PrivacyStringColor,"blue");
-   SuccessfulMsg=1;
+   SuccessfulMsg=true;
    TopUserFields=TOPUSERFIELDS_NUM | TOPUSERFIELDS_DATE_TIME | TOPUSERFIELDS_USERID | TOPUSERFIELDS_CONNECT |
                  TOPUSERFIELDS_BYTES | TOPUSERFIELDS_SETYB | TOPUSERFIELDS_IN_CACHE_OUT |
                  TOPUSERFIELDS_USED_TIME | TOPUSERFIELDS_MILISEC | TOPUSERFIELDS_PTIME |
@@ -231,18 +259,18 @@ int main(int argc,char *argv[])
    strcpy(DataFileDelimiter,";");
    DataFileFields=DATA_FIELD_USER | DATA_FIELD_DATE | DATA_FIELD_TIME | DATA_FIELD_URL | DATA_FIELD_CONNECT |
                   DATA_FIELD_BYTES | DATA_FIELD_IN_CACHE | DATA_FIELD_OUT_CACHE | DATA_FIELD_ELAPSED;
-   ShowReadStatistics=1;
+   ShowReadStatistics=true;
    strcpy(IndexSortOrder,"D");
-   ShowSargInfo=1;
-   ShowSargLogo=1;
+   ShowSargInfo=true;
+   ShowSargLogo=true;
    strcpy(ParsedOutputLog,"no");
    strcpy(ParsedOutputLogCompress,"/bin/gzip -f");
-   strcpy(DisplayedValues,"abbreviation");
+   DisplayedValues=DISPLAY_ABBREV;
    strcpy(HeaderFontSize,"9px");
    strcpy(TitleFontSize,"11px");
    strcpy(AuthUserTemplateFile,"sarg_htaccess");
    set_download_suffix("7z,ace,arj,avi,bat,bin,bz2,bzip,cab,com,cpio,dll,doc,dot,exe,gz,iso,lha,lzh,mdb,mov,mp3,mpeg,mpg,mso,nrg,ogg,ppt,rar,rtf,shs,src,sys,tar,tgz,vcd,vob,wma,wmv,zip");
-   Graphs=1;
+   Graphs=true;
 #if defined(FONTDIR)
    strcpy(GraphFont,FONTDIR"/DejaVuSans.ttf");
 #else
@@ -252,9 +280,9 @@ int main(int argc,char *argv[])
    NtlmUserFormat=NTLMUSERFORMAT_DOMAINUSER;
    IndexTree=INDEX_TREE_FILE;
    strcpy(RealtimeTypes,"GET,PUT,CONNECT");
-   strcpy(RealtimeUnauthRec,"show");
-   SquidguardIgnoreDate=0;
-   DansguardianIgnoreDate=0;
+   RealtimeUnauthRec=REALTIME_UNAUTH_REC_SHOW;
+   RedirectorIgnoreDate=false;
+   DansguardianIgnoreDate=false;
    DataFileUrl=DATAFILEURL_IP;
    strcpy(MaxElapsed,"28800000");
    BytesInSitesUsersReport=0;
@@ -312,33 +340,36 @@ int main(int argc,char *argv[])
    debug=0;
    debugz=0;
    debugm=0;
-   iprel=0;
-   userip=0;
-   color1=0;
-   color2=0;
-   color3=0;
-   realt=0;
+   iprel=false;
+   userip=false;
+   realt=false;
    realtime_refresh=3;
    realtime_access_log_lines=1000;
    cost=0.01;
    nocost=50000000;
    ndownload=0;
-   squid24=0;
+   squid24=false;
+   dfrom=0;
+   duntil=0;
 
    bzero(IncludeUsers, sizeof(IncludeUsers));
    bzero(ExcludeString, sizeof(ExcludeString));
    first_user_file=NULL;
+   memset(&period,0,sizeof(period));
 
    NAccessLog=0;
    for(x=0; x<MAXLOGS; x++)
       AccessLog[x][0]='\0';
    AccessLogFromCmdLine=0;
+   RedirectorLogFromCmdLine=0;
 
    strcpy(Title,_("Squid User Access Report"));
 
-   while((ch = getopt(argc, argv, "a:b:c:d:e:f:g:u:l:L:o:s:t:w:hijmnprvxyz")) != -1){
+   while((ch = getopt_long_only(argc, argv, "a:b:c:d:e:f:g:u:l:L:o:s:t:w:hijmnprvxyz",long_options,&option_index)) != -1){
       switch(ch)
       {
+         case 0:
+            break;
          case 'a':
             strcpy(addr,optarg);
             break;
@@ -351,14 +382,7 @@ int main(int argc,char *argv[])
          case 'd':
             strncpy(date,optarg,sizeof(date)-1);
             date[sizeof(date)-1]='\0';
-            getword_start(&gwarea,optarg);
-            if (getword(cdfrom,sizeof(cdfrom),&gwarea,'-')<0 || getword(cduntil,sizeof(cduntil),&gwarea,0)<0) {
-               printf(_("SARG: The date range requested on the command line by option -d is invalid.\n"));
-               exit(1);
-            }
-            date_from(date, cdfrom, cduntil);
-            dfrom=atoi(cdfrom);
-            duntil=atoi(cduntil);
+            date_from(date, &dfrom, &duntil);
             break;
          case 'e':
             strcpy(email,optarg);
@@ -371,37 +395,50 @@ int main(int argc,char *argv[])
             break;
          case 'h':
             usage(argv[0]);
-            exit(0);
-            break;
+            exit(EXIT_SUCCESS);
          case 'i':
-            iprel++;
+            iprel=true;
             break;
          case 'l':
             if (NAccessLog>=MAXLOGS) {
-               printf(_("SARG: Too many log files passed on command line with option -l.\n"));
-               exit(1);
+               debuga(_("Too many log files passed on command line with option -l.\n"));
+               exit(EXIT_FAILURE);
+            }
+            if (strlen(optarg)>=MAX_LOG_FILELEN) {
+               debuga(_("Log file name too long passed on command line with option -l: %s\n"),optarg);
+               exit(EXIT_FAILURE);
             }
             strcpy(AccessLog[NAccessLog],optarg);
             NAccessLog++;
             AccessLogFromCmdLine++;
             break;
          case 'L':
-            strcpy(SquidGuardLogAlternate,optarg);
+            if (NRedirectorLogs>MAX_REDIRECTOR_LOGS) {
+               debuga(_("Too many redirector logs passed on command line with option -L.\n"));
+               exit(EXIT_FAILURE);
+            }
+            if (strlen(optarg)>=MAX_REDIRECTOR_FILELEN) {
+               debuga(_("Redirector log file name too long passed on command line with opton -L: %s\n"),optarg);
+               exit(EXIT_FAILURE);
+            }
+            strcpy(RedirectorLogs[NRedirectorLogs],optarg);
+            NRedirectorLogs++;
+            RedirectorLogFromCmdLine++;
             break;
          case 'm':
             debugm++;
             break;
          case 'n':
-            dns++;
+            dns=true;
             break;
          case 'o':
             strcpy(outdir,optarg);
             break;
          case 'p':
-            userip++;
+            userip=true;
             break;
          case 'r':
-            realt++;
+            realt=true;
             break;
          case 's':
             strcpy(site,optarg);
@@ -415,19 +452,19 @@ int main(int argc,char *argv[])
               strcpy(hmf,optarg);
             } else {
                getword_start(&gwarea,optarg);
-               if (getword(hm,sizeof(hm),&gwarea,'-')<0 || getword(hmf,sizeof(hmf),&gwarea,0)<0) {
+               if (getword(hm,sizeof(hm),&gwarea,'-')<0 || getword(hmf,sizeof(hmf),&gwarea,'\0')<0) {
                   debuga(_("The time range passed on the command line with option -t is invalid\n"));
-                  exit(1);
+                  exit(EXIT_FAILURE);
                }
             }
             if(sscanf(hm,"%d:%d",&h,&m)!=2) {
                debuga(_("Time period must be MM or MM:SS. Exit\n"));
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             sprintf(hm,"%02d%02d",h,m);
             if(sscanf(hmf,"%d:%d",&h,&m)!=2) {
                debuga(_("Time period must be MM or MM:SS. Exit\n"));
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             sprintf(hmf,"%02d%02d",h,m);
             break;
@@ -450,41 +487,41 @@ int main(int argc,char *argv[])
          case 'z':
             debugz++;
             break;
-         case ':':
+         /*case ':':
             debuga(_("Option -%c require an argument\n"),optopt);
             errflg++;
-            break;
+            break;*/
          case '?':
             usage(argv[0]);
-            exit(1);
-            break;
+            exit(EXIT_FAILURE);
+         default:
+            abort();
       }
-
    }
 
-   if (errflg) {
+   if (errflg>0) {
       usage(argv[0]);
       exit(2);
    }
 
    if(debug) debuga(_("Init\n"));
 
-   if(ConfigFile[0] == '\0') sprintf(ConfigFile,"%s/sarg.conf",SYSCONFDIR);
+   if(ConfigFile[0] == '\0') snprintf(ConfigFile,sizeof(ConfigFile),"%s/sarg.conf",SYSCONFDIR);
    if(access(ConfigFile, R_OK) != 0) {
       debuga(_("Cannot open config file: %s - %s\n"),ConfigFile,strerror(errno));
-      exit(1);
+      exit(EXIT_FAILURE);
    }
 
    if(access(ConfigFile, R_OK) == 0)
       getconf();
 
-   if(UserIp) userip++;
+   if(userip) UserIp=true;
 
-   if(dns) Ip2Name=1;
+   if(dns) Ip2Name=true;
 
    if(realt) {
       realtime();
-      exit(0);
+      exit(EXIT_SUCCESS);
    }
 
    if(IndexTree == INDEX_TREE_FILE)
@@ -496,19 +533,22 @@ int main(int argc,char *argv[])
    if(DataFile[0] != '\0')
       dataonly++;
 
-   if(!NAccessLog) {
+   if(NAccessLog == 0) {
       strcpy(AccessLog[0],"/var/log/squid/access.log");
       NAccessLog++;
    }
 
-   if(strcmp(hexclude,"onvert") == 0 && strcmp(site,"plit") != 0) {
-      convlog(AccessLog[0], df, dfrom, duntil);
-      exit(0);
+   if(output_css) {
+      css_content(stdout);
+      exit(EXIT_SUCCESS);
    }
-
-   if(strcmp(site,"plit") == 0) {
-      splitlog(AccessLog[0], df, dfrom, duntil, hexclude);
-      exit(0);
+   if(split) {
+      splitlog(AccessLog[0], df, dfrom, duntil, convert);
+      exit(EXIT_SUCCESS);
+   }
+   if(convert) {
+      convlog(AccessLog[0], df, dfrom, duntil);
+      exit(EXIT_SUCCESS);
    }
 
    load_excludecodes(ExcludeCodes);
@@ -522,7 +562,7 @@ int main(int argc,char *argv[])
       strcpy(hexclude,ExcludeHosts);
    if(hexclude[0] != '\0') {
       gethexclude(hexclude,debug);
-      fhost++;
+      fhost=true;
    }
 
    if(ReportType == 0) {
@@ -533,7 +573,7 @@ int main(int argc,char *argv[])
 
    if(access(ExcludeUsers, R_OK) == 0) {
       getuexclude(ExcludeUsers,debug);
-      fuser++;
+      fuser=true;
    }
 
    indexonly=0;
@@ -561,13 +601,15 @@ int main(int argc,char *argv[])
       strcpy(df,"u");
       strcpy(DateFormat,"u");
    }
+   if (df[0]=='w')
+      IndexTree=INDEX_TREE_FILE;
 
    if(email[0] == '\0' && OutputEmail[0] != '\0') strcpy(email,OutputEmail);
 
    strcpy(tmp2,tmp);
 
    if(email[0] != '\0') {
-      sprintf(wtemp2,"%s/sarg",tmp2);
+      snprintf(wtemp2,sizeof(wtemp2),"%s/sarg",tmp2);
       my_mkdir(wtemp2);
       strcat(tmp2,"/sarg");
       strcpy(outdir,tmp2);
@@ -605,6 +647,8 @@ int main(int argc,char *argv[])
       debuga(_("                       IP report (-i) = %s\n"),(iprel) ? _("Yes") : _("No"));
       for (iarq=0 ; iarq<NAccessLog ; iarq++)
          debuga(_("                       Input log (-l) = %s\n"),AccessLog[iarq]);
+      for (iarq=0 ; iarq<NRedirectorLogs ; iarq++)
+         debuga(_("                  Redirector log (-L) = %s\n"),RedirectorLogs[iarq]);
       debuga(_("              Resolve IP Address (-n) = %s\n"),(Ip2Name) ? _("Yes") : _("No"));
       debuga(_("                      Output dir (-o) = %s\n"),outdir);
       debuga(_("Use Ip Address instead of userid (-p) = %s\n"),(UserIp) ? _("Yes") : _("No"));
@@ -634,6 +678,8 @@ int main(int argc,char *argv[])
       printf(_("                       IP report (-i) = %s\n"),(iprel) ? _("Yes") : _("No"));
       for (iarq=0 ; iarq<NAccessLog ; iarq++)
          printf(_("                       Input log (-l) = %s\n"),AccessLog[iarq]);
+      for (iarq=0 ; iarq<NRedirectorLogs ; iarq++)
+         printf(_("                  Redirector log (-L) = %s\n"),RedirectorLogs[iarq]);
       printf(_("              Resolve IP Address (-n) = %s\n"),(Ip2Name) ? _("Yes") : _("No"));
       printf(_("                      Output dir (-o) = %s\n"),outdir);
       printf(_("Use Ip Address instead of userid (-p) = %s\n"),(UserIp) ? _("Yes") : _("No"));
@@ -686,25 +732,25 @@ int main(int argc,char *argv[])
 
    init_usertab(UserTabFile);
 
-   if (longline_prepare(&line)<0) {
+   if ((line=longline_create())==NULL) {
       debuga(_("Not enough memory to read a log file\n"));
-      exit(1);
+      exit(EXIT_FAILURE);
    }
 
-   sprintf ( sz_Download_Unsort , "%s/sarg/download.unsort", tmp);
+   snprintf(sz_Download_Unsort,sizeof(sz_Download_Unsort),"%s/sarg/download.unsort", tmp);
 
    if(DataFile[0]=='\0') {
       if((ReportType & REPORT_TYPE_DENIED) != 0) {
          if((fp_denied=MY_FOPEN(denied_unsort,"w"))==NULL) {
-            debuga(_("SARG: (log) Cannot open file: %s - %s\n"),denied_unsort,strerror(errno));
-            exit(1);
+            debuga(_("(log) Cannot open file: %s - %s\n"),denied_unsort,strerror(errno));
+            exit(EXIT_FAILURE);
          }
       }
 
       if((ReportType & REPORT_TYPE_DENIED) != 0 || (ReportType & REPORT_TYPE_AUTH_FAILURES) != 0) {
          if((fp_authfail=MY_FOPEN(authfail_unsort,"w"))==NULL) {
-            debuga(_("SARG: (log) Cannot open file: %s - %s\n"),authfail_unsort,strerror(errno));
-            exit(1);
+            debuga(_("(log) Cannot open file: %s - %s\n"),authfail_unsort,strerror(errno));
+            exit(EXIT_FAILURE);
          }
       }
    }
@@ -718,50 +764,60 @@ int main(int argc,char *argv[])
          if(debug)
             debuga(_("Reading access log file: from stdin\n"));
          fp_in=stdin;
-         from_stdin=1;
+         from_stdin=true;
       } else {
-         decomp(arq,zip,tmp);
-         if(debug)
-            debuga(_("Reading access log file: %s\n"),arq);
-         if((fp_in=MY_FOPEN(arq,"r"))==NULL) {
-            debuga(_("SARG: (log) Cannot open log file: %s - %s\n"),arq,strerror(errno));
-            exit(1);
+         if (date[0]!='\0') {
+            if (stat(arq,&logstat)!=0) {
+               debuga(_("Cannot get the modification time of input log file %s (%s). Processing it anyway\n"),arq,strerror(errno));
+            } else {
+               struct tm *logtime=localtime(&logstat.st_mtime);
+               if ((logtime->tm_year+1900)*10000+(logtime->tm_mon+1)*100+logtime->tm_mday<dfrom) {
+                  debuga(_("Ignoring old log file %s\n"),arq);
+                  continue;
+               }
+            }
          }
-         from_stdin=0;
+         fp_in=decomp(arq,&from_pipe);
+         if(fp_in==NULL) {
+            debuga(_("(log) Cannot open log file: %s - %s\n"),arq,strerror(errno));
+            exit(EXIT_FAILURE);
+         }
+         if(debug) debuga(_("Reading access log file: %s\n"),arq);
+         from_stdin=false;
       }
       ilf=ILF_Unknown;
-      download_flag=0;
+      download_flag=false;
       // pre-read the file only if we have to show stats
-      if(ShowReadStatistics && !from_stdin) {
+      if(ShowReadStatistics && !from_stdin && !from_pipe) {
          size_t nread,i;
-         int skipcr=0;
+         bool skipcr=false;
+         char tmp4[MAXLEN];
 
          recs1=0UL;
          recs2=0UL;
 
-         while ((nread=fread(line.buffer,1,line.size,fp_in))>0) {
+         while ((nread=fread(tmp4,1,sizeof(tmp4),fp_in))>0) {
             for (i=0 ; i<nread ; i++)
                if (skipcr) {
-                  if (line.buffer[i]!='\n' && line.buffer[i]!='\r') {
-                     skipcr=0;
+                  if (tmp4[i]!='\n' && tmp4[i]!='\r') {
+                     skipcr=false;
                   }
                } else {
-                  if (line.buffer[i]=='\n' || line.buffer[i]=='\r') {
-                     skipcr=1;
+                  if (tmp4[i]=='\n' || tmp4[i]=='\r') {
+                     skipcr=true;
                      recs1++;
                   }
                }
          }
          rewind(fp_in);
-         printf(_("SARG: Records in file: %lu, reading: %3.2f%%\r"),recs1,(float) 0);
+         printf(_("SARG: Records in file: %lu, reading: %3.2f%%"),recs1,(float) 0);
+         putchar('\r');
          fflush( stdout ) ;
       }
 
-      line.start=0;
-      line.end=0;
-      line.length=0;
+      longline_reset(line);
 
-      while ((linebuf=longline_read(fp_in,&line))!=NULL) {
+      while ((linebuf=longline_read(fp_in,line))!=NULL) {
          blen=strlen(linebuf);
 
          if (ilf==ILF_Unknown) {
@@ -775,13 +831,10 @@ int main(int argc,char *argv[])
             }
 
             if(strncmp(linebuf,"*** SARG Log ***",16) == 0) {
-               getword_start(&gwarea,arqtt);
-               if (getword_skip(2000,&gwarea,'-')<0 || getword(val2,sizeof(val2),&gwarea,'_')<0 ||
-                   getword_skip(10,&gwarea,'-')<0 || getword(val3,sizeof(val3),&gwarea,'_')<0) {
+               if (getperiod_fromsarglog(arqtt,&period)<0) {
                   debuga(_("The name of the file is invalid: %s\n"),arq);
-                  exit(1);
+                  exit(EXIT_FAILURE);
                }
-               sprintf(period,"%s-%s",val2,val3);
                ilf=ILF_Sarg;
                ilf_count[ilf]++;
                continue;
@@ -794,17 +847,17 @@ int main(int argc,char *argv[])
             }
             sprintf(arq_log,"%s/sarg_temp.log",ParsedOutputLog);
             if((fp_log=MY_FOPEN(arq_log,"w"))==NULL) {
-               debuga(_("SARG: (log) Cannot open log file: %s - %s\n"),arq_log,strerror(errno));
-               exit(1);
+               debuga(_("(log) Cannot open log file: %s - %s\n"),arq_log,strerror(errno));
+               exit(EXIT_FAILURE);
             }
             fputs("*** SARG Log ***\n",fp_log);
          }
 
          recs2++;
-         if( ShowReadStatistics && !from_stdin && ! --OutputNonZero) {
-           perc = recs2 * 100 ;
-           perc = perc / recs1 ;
-           printf("SARG: Records in file: %lu, reading: %3.2f%%\r",recs1,perc);
+         if( ShowReadStatistics && !from_stdin && --OutputNonZero<=0) {
+           double perc = recs2 * 100. / recs1 ;
+           printf(_("SARG: Records in file: %lu, reading: %3.2lf%%"),recs1,perc);
+           putchar('\r');
            fflush (stdout);
            OutputNonZero = REPORT_EVERY_X_LINES ;
          }
@@ -815,18 +868,20 @@ int main(int argc,char *argv[])
 
          // exclude_string
          if(ExcludeString[0] != '\0') {
-            exstring=0;
+            bool exstring=false;
             getword_start(&gwarea,ExcludeString);
             while(strchr(gwarea.current,':') != 0) {
                if (getword_multisep(val1,sizeof(val1),&gwarea,':')<0) {
                   debuga(_("Maybe you have a broken record or garbage in your exclusion string\n"));
-                  exit(1);
+                  exit(EXIT_FAILURE);
+               }
+               if((str=(char *) strstr(linebuf,val1)) != (char *) NULL ) {
+                  exstring=true;
+                  break;
                }
-               if((str=(char *) strstr(linebuf,val1)) != (char *) NULL )
-                  exstring++;
             }
-            if((str=(char *) strstr(linebuf,gwarea.current)) != (char *) NULL )
-                  exstring++;
+            if(!exstring && (str=(char *) strstr(linebuf,gwarea.current)) != (char *) NULL )
+                  exstring=true;
             if(exstring) continue;
          }
 
@@ -834,141 +889,202 @@ int main(int argc,char *argv[])
          if(debugm)
             printf("BUF=%s\n",linebuf);
 
+         t=NULL;
          if (ilf==ILF_Squid || ilf==ILF_Common || ilf==ILF_Unknown) {
             getword_start(&gwarea,linebuf);
             if (getword(data,sizeof(data),&gwarea,' ')<0) {
-               debuga(_("Maybe you have a broken time in your access.log file.\n"));
-               exit(1);
+               debuga(_("Maybe you have a broken time in your access.log file\n"));
+               exit(EXIT_FAILURE);
             }
-            if((str=(char *) strchr(data, '.')) != (char *) NULL ) {
-               if((str=(char *) strchr(str+1, '.')) != (char *) NULL ) {
-                  strcpy(ip,data);
-                  strcpy(elap,"0");
-                  if(squid24) {
-                     if (getword(user,sizeof(user),&gwarea,' ')<0 || getword_skip(255,&gwarea,' ')<0) {
-                        debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                        exit(1);
-                     }
-                  } else {
-                     if (getword_skip(255,&gwarea,' ')<0 || getword(user,sizeof(user),&gwarea,' ')<0) {
-                        debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                        exit(1);
-                     }
-                  }
-                  if (getword(data,sizeof(data),&gwarea,']')<0 || getword_skip(MAXLEN,&gwarea,'"')<0 ||
-                      getword(fun,sizeof(fun),&gwarea,' ')<0) {
+            if((str=(char *) strchr(data, '.')) != (char *) NULL && (str=(char *) strchr(str+1, '.')) != (char *) NULL ) {
+               strcpy(ip,data);
+               strcpy(elap,"0");
+               if(squid24) {
+                  if (getword(user,sizeof(user),&gwarea,' ')<0 || getword_skip(255,&gwarea,' ')<0) {
                      debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
-                  if (getword_ptr(linebuf,&url,&gwarea,' ')<0) {
-                     debuga(_("Maybe you have a broken url in your %s file\n"),arq);
-                     exit(1);
+               } else {
+                  if (getword_skip(255,&gwarea,' ')<0 || getword(user,sizeof(user),&gwarea,' ')<0) {
+                     debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
+                     exit(EXIT_FAILURE);
                   }
-                  if (getword_skip(MAXLEN,&gwarea,' ')<0 || getword(code2,sizeof(code2),&gwarea,' ')<0 ||
-                      getword(tam,sizeof(tam),&gwarea,' ')<0) {
+               }
+               if (getword(data,sizeof(data),&gwarea,']')<0 || getword_skip(MAXLEN,&gwarea,'"')<0 ||
+                     getword(fun,sizeof(fun),&gwarea,' ')<0) {
+                  debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if (getword_ptr(linebuf,&url,&gwarea,' ')<0) {
+                  debuga(_("Maybe you have a broken url in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if (getword_skip(MAXLEN,&gwarea,' ')<0) {
+                  debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if (getword(code2,sizeof(code2),&gwarea,' ')<0) {
+                  debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if (getword(tam,sizeof(tam),&gwarea,' ')<0) {
+                  debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if((str=(char *) strchr(gwarea.current, ' ')) != (char *) NULL ) {
+                  if (getword(code,sizeof(code),&gwarea,' ')<0) {
                      debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
-                  if((str=(char *) strchr(gwarea.current, ' ')) != (char *) NULL ) {
-                     if (getword(code,sizeof(code),&gwarea,' ')<0) {
-                        debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                        exit(1);
-                     }
-                  } else {
-                     if (getword(code,sizeof(code),&gwarea,'\0')<0) {
-                        debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                        exit(1);
-                     }
+               } else {
+                  if (getword(code,sizeof(code),&gwarea,'\0')<0) {
+                     debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
+                     exit(EXIT_FAILURE);
                   }
+               }
 
-                  if ((str = strchr(code, ':')) != NULL)
-                     *str = '/';
+               if ((str = strchr(code, ':')) != NULL)
+                  *str = '/';
 
-                  if(strcmp(tam,"\0") == 0)
-                     strcpy(tam,"0");
+               if(strcmp(tam,"\0") == 0)
+                  strcpy(tam,"0");
 
-                  ilf=ILF_Common;
-                  ilf_count[ilf]++;
+               ilf=ILF_Common;
+               ilf_count[ilf]++;
+
+               getword_start(&gwarea,data+1);
+               if (getword_multisep(data,sizeof(data),&gwarea,':')<0){
+                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if (getword_multisep(hora,sizeof(hora),&gwarea,' ')<0){
+                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               getword_start(&gwarea,data);
+               if (getword_atoll(&iday,&gwarea,'/')<0){
+                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
+               if (getword(mes,sizeof(mes),&gwarea,'/')<0){
+                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+               if (getword_atoll(&iyear,&gwarea,'/')<0){
+                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
+               }
+
+               imonth=month2num(mes)+1;
+               idata=builddia(iday,imonth,iyear);
+               computedate(iyear,imonth,iday,&tt);
+               t=&tt;
             }
 
             if(ilf==ILF_Unknown || ilf==ILF_Squid) {
                if (getword(elap,sizeof(elap),&gwarea,' ')<0) {
-                  debuga(_("Maybe you have a broken elapsed time in your %s file.\n"),arq);
-                  exit(1);
+                  debuga(_("Maybe you have a broken elapsed time in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
                while(strcmp(elap,"") == 0 && gwarea.current[0] != '\0')
                   if (getword(elap,sizeof(elap),&gwarea,' ')<0) {
-                     debuga(_("Maybe you have a broken elapsed time in your %s file.\n"),arq);
-                     exit(1);
+                     debuga(_("Maybe you have a broken elapsed time in your %s file\n"),arq);
+                     exit(EXIT_FAILURE);
                   }
                if(strlen(elap) < 1) continue;
                if (getword(ip,sizeof(ip),&gwarea,' ')<0){
-                  debuga(_("Maybe you have a broken client IP address in your %s file.\n"),arq);
-                  exit(1);
+                  debuga(_("Maybe you have a broken client IP address in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
                if (getword(code,sizeof(code),&gwarea,' ')<0){
-                  debuga(_("Maybe you have a broken result code in your %s file.\n"),arq);
-                  exit(1);
+                  debuga(_("Maybe you have a broken result code in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
                if (getword(tam,sizeof(tam),&gwarea,' ')<0){
-                  debuga(_("Maybe you have a broken amount of data in your %s file.\n"),arq);
-                  exit(1);
+                  debuga(_("Maybe you have a broken amount of data in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
                if (getword(fun,sizeof(fun),&gwarea,' ')<0){
-                  debuga(_("Maybe you have a broken request method in your %s file.\n"),arq);
-                  exit(1);
+                  debuga(_("Maybe you have a broken request method in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
                if (getword_ptr(linebuf,&url,&gwarea,' ')<0){
                   debuga(_("Maybe you have a broken url in your %s file\n"),arq);
-                  exit(1);
+                  exit(EXIT_FAILURE);
                }
                if (getword(user,sizeof(user),&gwarea,' ')<0){
-                  debuga(_("Maybe you have a broken user ID in your %s file.\n"),arq);
-                  exit(1);
+                  debuga(_("Maybe you have a broken user ID in your %s file\n"),arq);
+                  exit(EXIT_FAILURE);
                }
                ilf=ILF_Squid;
                ilf_count[ilf]++;
+
+               tnum=atoi(data);
+               t=localtime(&tnum);
+               if (t == NULL) {
+                  debuga(_("Cannot convert the timestamp from the squid log file\n"));
+                  exit(EXIT_FAILURE);
+               }
+
+               strftime(tbuf2, sizeof(tbuf2), "%H%M", t);
+
+               idata=(t->tm_year+1900)*10000+(t->tm_mon+1)*100+t->tm_mday;
             }
          }
          if (ilf==ILF_Sarg) {
             getword_start(&gwarea,linebuf);
             if (getword(data,sizeof(data),&gwarea,'\t')<0){
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(hora,sizeof(hora),&gwarea,'\t')<0) {
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(user,sizeof(user),&gwarea,'\t')<0) {
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(ip,sizeof(ip),&gwarea,'\t')<0) {
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword_ptr(linebuf,&url,&gwarea,'\t')<0){
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(tam,sizeof(tam),&gwarea,'\t')<0){
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(code,sizeof(code),&gwarea,'\t')<0){
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(elap,sizeof(elap),&gwarea,'\t')<0){
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if (getword(smartfilter,sizeof(smartfilter),&gwarea,'\0')<0){
                debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+               exit(EXIT_FAILURE);
+            }
+            getword_start(&gwarea,data);
+            if (getword_atoll(&iday,&gwarea,'/')<0 || iday<1 || iday>31){
+               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+               exit(EXIT_FAILURE);
+            }
+            if (getword_atoll(&imonth,&gwarea,'/')<0 || imonth<1 || imonth>12){
+               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+               exit(EXIT_FAILURE);
+            }
+            if (getword_atoll(&iyear,&gwarea,'\0')<0){
+               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
+               exit(EXIT_FAILURE);
             }
+            idata=builddia(iday,imonth,iyear);
+            computedate(iyear,imonth,iday,&tt);
+            t=&tt;
          }
          if (ilf==ILF_Isa) {
             if (linebuf[0] == '#') {
@@ -979,14 +1095,14 @@ int main(int argc,char *argv[])
                // remove the #Fields: column at the beginning of the line
                if (getword_skip(1000,&gwarea,' ')<0){
                   debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                  exit(1);
+                  exit(EXIT_FAILURE);
                }
                for (ncols=0 ; ncols<ISACOL_Last ; ncols++) cols[ncols]=-1;
                ncols=0;
                while(gwarea.current[0] != '\0') {
                   if (getword(val1,sizeof(val1),&gwarea,'\t')<0){
                      debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   if(strcmp(val1,"c-ip") == 0) cols[ISACOL_Ip]=ncols;
                   if(strcmp(val1,"cs-username") == 0) cols[ISACOL_UserName]=ncols;
@@ -1010,42 +1126,42 @@ int main(int argc,char *argv[])
             for (x=0 ; x<isa_ncols ; x++) {
                if (getword_ptr(linebuf,&str,&gwarea,'\t')<0) {
                   debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-                  exit(1);
+                  exit(EXIT_FAILURE);
                }
                if (x==isa_cols[ISACOL_Ip]) {
                   if (strlen(str)>=sizeof(ip)) {
                      debuga(_("Maybe you have a broken IP in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(ip,str);
                } else if (x==isa_cols[ISACOL_UserName]) {
                   if (strlen(str)>=sizeof(user)) {
-                     debuga(_("Maybe you have a broken user in your %s file\n"),arq);
-                     exit(1);
+                     debuga(_("Maybe you have a broken user ID in your %s file\n"),arq);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(user,str);
                } else if (x==isa_cols[ISACOL_Date]) {
                   if (strlen(str)>=sizeof(data)) {
                      debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(data,str);
                } else if (x==isa_cols[ISACOL_Time]) {
                   if (strlen(str)>=sizeof(hora)) {
                      debuga(_("Maybe you have a broken time in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(hora,str);
                } else if (x==isa_cols[ISACOL_TimeTaken]) {
                   if (strlen(str)>=sizeof(elap)) {
                      debuga(_("Maybe you have a broken download duration in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(elap,str);
                } else if (x==isa_cols[ISACOL_Bytes]) {
                   if (strlen(str)>=sizeof(tam)) {
                      debuga(_("Maybe you have a broken download size in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(tam,str);
                } else if (x==isa_cols[ISACOL_Uri]) {
@@ -1053,7 +1169,7 @@ int main(int argc,char *argv[])
                } else if (x==isa_cols[ISACOL_Status]) {
                   if (strlen(str)>=sizeof(code)) {
                      debuga(_("Maybe you have a broken access code in your %s file\n"),arq);
-                     exit(1);
+                     exit(EXIT_FAILURE);
                   }
                   strcpy(code,str);
                }
@@ -1064,110 +1180,30 @@ int main(int argc,char *argv[])
                strcpy(code,val1);
             }
             getword_start(&gwarea,data);
-            if (getword(ano,sizeof(ano),&gwarea,'-')<0){
-               debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
-            }
-            if (getword(mes,sizeof(mes),&gwarea,'-')<0){
-               debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+            if (getword_atoll(&iyear,&gwarea,'-')<0){
+               debuga(_("Maybe you have a broken year in your %s file\n"),arq);
+               exit(EXIT_FAILURE);
             }
-            if (getword(dia,sizeof(dia),&gwarea,'\0')<0){
-               debuga(_("Maybe you have a broken record or garbage in your %s file\n"),arq);
-               exit(1);
+            if (getword_atoll(&imonth,&gwarea,'-')<0){
+               debuga(_("Maybe you have a broken month in your %s file\n"),arq);
+               exit(EXIT_FAILURE);
             }
-            conv_month_name(mes);
-            sprintf(data," %s/%s/%s:%s",dia,mes,ano,hora);
-         }
-
-         if(ilf==ILF_Squid) {
-            tt=atoi(data);
-            t=localtime(&tt);
-
-            strftime(tbuf2, sizeof(tbuf2), "%H%M", t);
-            sprintf(mes,"%d",t->tm_mon+1);
-            conv_month_name(mes);
-            if(strncmp(df,"u",1) == 0)
-               sprintf(tbuf, "%04d%s%02d", t->tm_year+1900, mes, t->tm_mday);
-            if(strncmp(df,"e",1) == 0)
-               sprintf(tbuf, "%02d%s%04d", t->tm_mday, mes, t->tm_year+1900);
-            if(strncmp(df,"w",1) == 0) {
-               IndexTree=INDEX_TREE_FILE;
-               strftime(tbuf, sizeof(tbuf), "%Y.%U", t);
+            if (getword_atoll(&iday,&gwarea,'\0')<0){
+               debuga(_("Maybe you have a broken day in your %s file\n"),arq);
+               exit(EXIT_FAILURE);
             }
 
-            strftime(wdata, sizeof(wdata), "%Y%m%d", t);
-            idata=atoi(wdata);
-
-            if(strncmp(df,"u",1)==0)
-               strftime(dia, sizeof(dia), "%m/%d/%Y", t);
-            else
-               strftime(dia, sizeof(dia), "%d/%m/%Y", t);
-            sprintf(hora,"%02d:%02d:%02d",t->tm_hour,t->tm_min,t->tm_sec);
-         } else if(ilf==ILF_Common || ilf==ILF_Isa) {
-            getword_start(&gwarea,data+1);
-            if (getword_multisep(data,sizeof(data),&gwarea,':')<0){
-               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-               exit(1);
-            }
-            if (getword_multisep(hora,sizeof(hora),&gwarea,' ')<0){
-               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-               exit(1);
-            }
-            getword_start(&gwarea,data);
-            if (getword(dia,sizeof(dia),&gwarea,'/')<0){
-               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-               exit(1);
-            }
-            if (getword(mes,sizeof(mes),&gwarea,'/')<0){
-               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-               exit(1);
-            }
-            if (getword(ano,sizeof(ano),&gwarea,'/')<0){
-               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-               exit(1);
-            }
-
-            if(strcmp(df,"u") == 0)
-               snprintf(tbuf,sizeof(tbuf),"%s%s%s",ano,mes,dia);
-            if(strcmp(df,"e") == 0)
-               snprintf(tbuf,sizeof(tbuf),"%s%s%s",dia,mes,ano);
-            builddia(dia,mes,ano,df,wdata);
-            idata=atoi(wdata);
-            tt=computedate(ano,mes,dia);
-            t=localtime(&tt);
-         } else if (ilf==ILF_Sarg) {
-            getword_start(&gwarea,data);
-            if(strcmp(df,"u") == 0) {
-               if (getword(mes,sizeof(mes),&gwarea,'/')<0){
-                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-                  exit(1);
-               }
-               if (getword(dia,sizeof(dia),&gwarea,'/')<0){
-                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-                  exit(1);
-               }
-            } else {
-               if (getword(dia,sizeof(dia),&gwarea,'/')<0){
-                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-                  exit(1);
-               }
-               if (getword(mes,sizeof(mes),&gwarea,'/')<0){
-                  debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-                  exit(1);
-               }
-            }
-            if (getword(ano,sizeof(ano),&gwarea,0)<0){
-               debuga(_("Maybe you have a broken date in your %s file\n"),arq);
-               exit(1);
-            }
-            snprintf(wdata,9,"%s%s%s",ano,mes,dia);
-            idata=atoi(wdata);
-            tt=computedate(ano,mes,dia);
-            t=localtime(&tt);
-         } else {
-            t=NULL;
+            idata=builddia(iday,imonth,iyear);
+            computedate(iyear,imonth,iday,&tt);
+            t=&tt;
          }
+         if (t==NULL) {
+            debuga(_("Unknown input log file format\n"));
+            break;
+         }
+
+         strftime(dia, sizeof(dia), "%d/%m/%Y", t);
+         snprintf(hora,sizeof(hora),"%02d:%02d:%02d",t->tm_hour,t->tm_min,t->tm_sec);
 
          if(debugm)
             printf("DATE=%s IDATA=%d DFROM=%d DUNTIL=%d\n",date,idata,dfrom,duntil);
@@ -1249,7 +1285,7 @@ int main(int argc,char *argv[])
                download_count++;
             }
          } else
-            download_flag=0;
+            download_flag=false;
 
          // remove any protocol:// at the beginning of the URL
          if ((str = strchr(url,'/')) != NULL && str[1] == '/') {
@@ -1286,7 +1322,7 @@ int main(int argc,char *argv[])
             while(chm) {
                if (getword_multisep(warea,sizeof(warea),&gwarea,':')<0){
                   debuga(_("Maybe you have a broken time in your %s file\n"),arq);
-                  exit(1);
+                  exit(EXIT_FAILURE);
                }
                strncat(hmr,warea,2);
                chm--;
@@ -1300,15 +1336,15 @@ int main(int argc,char *argv[])
             if(strstr(url,site)==0) continue;
          }
 
-         if(userip) {
+         if(UserIp) {
             strcpy(user,ip);
-            id_is_ip=1;
+            id_is_ip=true;
          } else {
-            id_is_ip=0;
+            id_is_ip=false;
             if(strcmp(user,"-") == 0 || strcmp(user," ") == 0 || strcmp(user,"") == 0) {
                if(RecordsWithoutUser == RECORDWITHOUTUSER_IP) {
                   strcpy(user,ip);
-                  id_is_ip=1;
+                  id_is_ip=true;
                }
                if(RecordsWithoutUser == RECORDWITHOUTUSER_IGNORE)
                   continue;
@@ -1372,7 +1408,7 @@ int main(int argc,char *argv[])
             ufile=malloc(sizeof(*ufile));
             if (!ufile) {
                debuga(_("Not enough memory to store the user %s\n"),user);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             memset(ufile,0,sizeof(*ufile));
             ufile->next=first_user_file;
@@ -1394,7 +1430,10 @@ int main(int argc,char *argv[])
                for (ufile1=first_user_file ; ufile1 ; ufile1=ufile1->next) {
                   if (ufile1->file!=NULL) {
                      if (x>=maxopenfiles) {
-                        fclose(ufile1->file);
+                        if (fclose(ufile1->file)==EOF) {
+                           debuga(_("Failed to close the log file of user %s - %s\n"),ufile1->user->id,strerror(errno));
+                           exit(EXIT_FAILURE);
+                        }
                         ufile1->file=NULL;
                      }
                      x++;
@@ -1403,7 +1442,7 @@ int main(int argc,char *argv[])
             }
             if (snprintf (tmp3, sizeof(tmp3), "%s/sarg/%s.unsort", tmp, ufile->user->filename)>=sizeof(tmp3)) {
                debuga(_("Temporary user file name too long: %s/sarg/%s.unsort\n"), tmp, ufile->user->filename);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
             if ((ufile->file = MY_FOPEN (tmp3, "a")) == NULL) {
                debuga(_("(log) Cannot open temporary file: %s - %s\n"), tmp3, strerror(errno));
@@ -1422,7 +1461,10 @@ int main(int argc,char *argv[])
             }
             strcpy( sz_Last_User , user ) ;
          }*/
-         fprintf(ufile->file, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",dia,hora,ip,url,tam,code,elap,smartfilter);
+         if (fprintf(ufile->file, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",dia,hora,ip,url,tam,code,elap,smartfilter)<=0) {
+            debuga(_("Write error in the log file of user %s\n"),user);
+            exit(EXIT_FAILURE);
+         }
 
          if(fp_log && ilf!=ILF_Sarg)
             fprintf(fp_log, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",dia,hora,user,ip,url,tam,code,elap,smartfilter);
@@ -1452,17 +1494,17 @@ int main(int argc,char *argv[])
             }
          }
 
-         if((!totper || idata<mindate) && ilf!=ILF_Sarg){
-            totper++;
-            mindate=idata;
-            sprintf(period,"%s-",tbuf);
-            strcpy(start_hour,tbuf2);
-            if(date[0] != '\0')
-               fixper(tbuf, period, cduntil);
-            if(debugz){
-               debugaz("tbuf",tbuf);
-               debugaz("period",period);
+         if (ilf!=ILF_Sarg) {
+            if(!totper || idata<mindate){
+               mindate=idata;
+               memcpy(&period.start,t,sizeof(*t));
+               strcpy(start_hour,tbuf2);
+            }
+            if (!totper || idata>maxdate) {
+               maxdate=idata;
+               memcpy(&period.end,t,sizeof(*t));
             }
+            totper=true;
          }
 
          if(debugm){
@@ -1478,13 +1520,19 @@ int main(int argc,char *argv[])
          }
       }
       if (!from_stdin) {
-         fclose(fp_in);
+         if (from_pipe)
+            pclose(fp_in);
+         else
+            fclose(fp_in);
          if( ShowReadStatistics )
             printf(_("SARG: Records in file: %lu, reading: %3.2f%%\n"),recs1, (float) 100 );
       }
    }
 
-   longline_free(&line);
+   if (debug)
+      debuga(_("   Records read: %ld, written: %ld, excluded: %ld\n"),totregsl,totregsg,totregsx);
+
+   longline_destroy(&line);
    if ( fp_Download_Unsort )
      fclose (fp_Download_Unsort);
 
@@ -1503,8 +1551,6 @@ int main(int argc,char *argv[])
 
       for (ilf=0 ; ilf<ILF_Last ; ilf++) totalcount+=ilf_count[ilf];
 
-      debuga(_("   Records read: %ld, written: %ld, excluded: %ld\n"),totregsl,totregsg,totregsx);
-
       if(ilf_count[ILF_Common]>0 && ilf_count[ILF_Squid]>0)
          debuga(_("Log with mixed records format (squid and common log)\n"));
 
@@ -1517,53 +1563,41 @@ int main(int argc,char *argv[])
       if(ilf_count[ILF_Sarg]>0)
          debuga(_("Sarg log format\n"));
 
-      if(totalcount==0) {
-         if(!totregsg) {
-            debuga(_("No records found\n"));
-            debuga(_("End\n"));
-         } else debuga(_("Log with invalid format\n"));
-         if(fp_denied)
-            fclose(fp_denied);
-         if(fp_authfail)
-            fclose(fp_authfail);
-         userinfo_free();
-         if(userfile)
-            free(userfile);
-         close_usertab();
-         unlink(denied_unsort);
-         unlink(authfail_unsort);
-         unlink(tmp3);
-         exit(0);
-      }
+      if(totalcount==0 && totregsg)
+         debuga(_("Log with invalid format\n"));
    }
 
    if(!totregsg){
       debuga(_("No records found\n"));
       debuga(_("End\n"));
-//      fclose(fp_ou);
-      if(fp_denied)
-         fclose(fp_denied);
-      if(fp_authfail)
-         fclose(fp_authfail);
+      if(fp_denied) fclose(fp_denied);
+      if(fp_authfail) fclose(fp_authfail);
       userinfo_free();
-      if(userfile)
-         free(userfile);
+      if(userfile) free(userfile);
       close_usertab();
-      exit(0);
+      exit(EXIT_SUCCESS);
    }
 
-   if(date[0] == '\0' && ilf_count[ILF_Sarg]==0) {
-      strcat(period,tbuf);
+   if (date[0]!='\0') {
+      char date0[30], date1[30];
+
+      strftime(date0,sizeof(date0),"%d/%m/%Y",&period.start);
+      strftime(date1,sizeof(date1),"%d/%m/%Y",&period.end);
+      debuga(_("Period covered by log files: %s-%s\n"),date0,date1);
+      getperiod_fromrange(&period,dfrom,duntil);
+   }
+   if (getperiod_buildtext(&period)<0) {
+      debuga(_("Failed to build the string representation of the date range\n"));
+      exit(EXIT_FAILURE);
    }
 
    if(debugz){
       debugaz("data",dia);
-      debugaz("tbuf",tbuf);
-      debugaz("period",period);
+      debugaz("period",period.text);
    }
 
    if(debug)
-      debuga(_("Period: %s\n"),period);
+      debuga(_("Period: %s\n"),period.text);
 
 //   fclose(fp_ou);
    if(fp_denied)
@@ -1574,15 +1608,8 @@ int main(int argc,char *argv[])
    if(fp_log != NULL) {
       fclose(fp_log);
       strcpy(end_hour,tbuf2);
-      getword_start(&gwarea,period);
-      if (getword(val2,sizeof(val2),&gwarea,'-')<0){
-         debuga(_("Maybe you have a broken date range definition.\n"));
-         exit(1);
-      }
-      if (getword(val1,sizeof(val1),&gwarea,'\0')<0){
-         debuga(_("Maybe you have a broken date range definition.\n"));
-         exit(1);
-      }
+      strftime(val2,sizeof(val2),"%d%m%Y",&period.start);
+      strftime(val1,sizeof(val1),"%d%m%Y",&period.end);
       sprintf(val4,"%s/sarg-%s_%s-%s_%s.log",ParsedOutputLog,val2,start_hour,val1,end_hour);
       if (rename(arq_log,val4)) {
          debuga(_("failed to rename %s to %s - %s\n"),arq_log,val4,strerror(errno));
@@ -1599,7 +1626,7 @@ int main(int argc,char *argv[])
             if (!WIFEXITED(cstatus) || WEXITSTATUS(cstatus)) {
                debuga(_("command return status %d\n"),WEXITSTATUS(cstatus));
                debuga(_("command: %s\n"),val1);
-               exit(1);
+               exit(EXIT_FAILURE);
             }
          }
       }
@@ -1613,7 +1640,7 @@ int main(int argc,char *argv[])
       if (!WIFEXITED(cstatus) || WEXITSTATUS(cstatus)) {
          debuga(_("sort command return status %d\n"),WEXITSTATUS(cstatus));
          debuga(_("sort command: %s\n"),csort);
-         exit(1);
+         exit(EXIT_FAILURE);
       }
       unlink(denied_unsort);
    }
@@ -1629,11 +1656,6 @@ int main(int argc,char *argv[])
    if((ReportType & REPORT_TYPE_DENIED) != 0)
       unlink(denied_sort);
 
-   if(zip[0] != '\0' && strcmp(zip,"zcat") !=0) {
-      recomp(arq, zip);
-   }
-//   else  unlink(arq);
-
    if(strcmp(tmp,"/tmp") != 0) {
       unlinkdir(tmp,0);
    }
@@ -1646,7 +1668,7 @@ int main(int argc,char *argv[])
    if(debug)
       debuga(_("End\n"));
 
-   exit(0);
+   exit(EXIT_SUCCESS);
 
 }
 
@@ -1660,25 +1682,31 @@ static void getusers(const char *pwdfile, int debug)
    long int nreg=0;
 
    if(debug)
-      debuga(_("Loading password file from: %s\n"),pwdfile);
+      debuga(_("Loading password file from %s\n"),pwdfile);
 
    if ((fp_usr = fopen(pwdfile, "r")) == NULL) {
-      debuga(_("(getusers) Cannot open file: %s - %s\n"),pwdfile,strerror(errno));
-      exit(1);
+      debuga(_("(getusers) Cannot open file %s - %s\n"),pwdfile,strerror(errno));
+      exit(EXIT_FAILURE);
    }
 
-   fseek(fp_usr, 0, SEEK_END);
+   if (fseek(fp_usr, 0, SEEK_END)==-1) {
+      debuga(_("Failed to move till the end of the users file %s: %s\n"),pwdfile,strerror(errno));
+      exit(EXIT_FAILURE);
+   }
    nreg = ftell(fp_usr);
    if (nreg<0) {
       debuga(_("Cannot get the size of file %s\n"),pwdfile);
-      exit(1);
+      exit(EXIT_FAILURE);
    }
    nreg = nreg+5000;
-   fseek(fp_usr, 0, SEEK_SET);
+   if (fseek(fp_usr, 0, SEEK_SET)==-1) {
+      debuga(_("Failed to rewind the users file %s: %s\n"),pwdfile,strerror(errno));
+      exit(EXIT_FAILURE);
+   }
 
    if((userfile=(char *) malloc(nreg))==NULL){
-      debuga(_("malloc error (%ld):\n"),nreg);
-      exit(1);
+      debuga(_("malloc error (%ld)\n"),nreg);
+      exit(EXIT_FAILURE);
    }
 
    bzero(userfile,nreg);
@@ -1687,10 +1715,10 @@ static void getusers(const char *pwdfile, int debug)
    while(fgets(buf,sizeof(buf),fp_usr)!=NULL) {
       str=strchr(buf,':');
       if (!str) {
-         debuga(_("You have an invalid user in your %s file.\n"),pwdfile);
-         exit(1);
+         debuga(_("You have an invalid user in your %s file\n"),pwdfile);
+         exit(EXIT_FAILURE);
       }
-      str[1]=0;
+      str[1]='\0';
       strcat(userfile,buf);
    }