"suppkral" condition remove as being not used.
[timeplan.git] / timeplan.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <getopt.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <time.h>
7 #include <assert.h>
8 #include <limits.h>
9 #include <ctype.h>
10 #include <regex.h>
11
12 #define ACTS_MAX 20
13 #define HASH_SIZE 971
14 #define CONFIGFILE "/.timeplanrc" /* HOME prepended */
15 #define DEF_TIMEPLAN "/.timeplan" /* HOME prepended */
16 #define MARK_DAY "_days"
17 #define DEF_FORMTOTAL ":6"
18 #define LENGTH(x) (sizeof((x))/sizeof(*(x)))
19 #define WHERE1 " in \"%s\" on line %d!\n"
20 #define WHERE2 finame,line
21 #define NL "\r\n"
22 #define ERRH1 stderr,"%s: "
23 #define ERRH2 pname
24 #define ERRNO1 ": %s!\n"
25 #define ERRNO2 strerror(errno)
26 #define FAKEUSE =0
27
28 static const char version[]="This is TimePlan, version 1.0\n";
29 static const char *pname;
30 static char *finame;
31 static FILE *fi;
32 static int verbose=0,tree=0,doaverage=0;
33 static char *formtotal=DEF_FORMTOTAL;
34 static char buf[LINE_MAX];
35 static int line=0;
36 static enum { SORT_NO,SORT_TIMETOT,SORT_STORES } sortby=SORT_TIMETOT;
37 static unsigned lifetime_days=0;
38 static unsigned long lifetime_seq=1;
39
40 static void usage(void)
41 {
42         fprintf(stderr,"\
43 %s\
44 This command summarizes the timelog information:\n\
45 \n\
46 Usage: timeplan [-u|--unsort] [-s|--stores] [-T|--timetot]  [-t|--tree]\n\
47                 [-c|--condition <cond>] [-f|--formtotal <fmtstring>]\n\
48                 [-r|--rule <ruleL>:<ruleR>]\n\
49                 [-v|--verbose] [-h|--help] [-V|--version]\n\
50 \n\
51   -u, --unsort\t\tDon't sort the result in any way\n\
52   -s, --stores\t\tSort the result by stores count\n\
53   -T, --timetot\t\tSort the result by total time (default)\n\
54   -t, --tree\t\tOrganize data as hierarchy tree\n\
55   -a, --average\t\tDisplay all times as average-per-day value\n\
56   -c, --condition\tDefine condition variable\n\
57   -f, --formtotal\tFormat \"Total\" column (\"text *val/val:width text\")\n\
58   -r, --rule\t\tAdd to the end of .rc file this rule (':'->'\\t')\n\
59   -v, --verbose\t\tInform about phases of transfer\n\
60   -h, --help\t\tPrint a summary of the options\n\
61   -V, --version\t\tPrint the version number\n\
62 ",version);
63         exit(EXIT_FAILURE);
64 }
65
66 static const struct option longopts[]={
67 {"unsort"   ,0,0,'u'},
68 {"stores"   ,0,0,'s'},
69 {"timetot"  ,0,0,'T'},
70 {"tree"     ,0,0,'t'},
71 {"average"  ,0,0,'a'},
72 {"condition",1,0,'c'},
73 {"formtotal",1,0,'f'},
74 {"rule"     ,1,0,'r'},
75 {"verbose"  ,0,0,'v'},
76 {"help"     ,0,0,'h'},
77 {"version"  ,0,0,'V'}};
78
79 static int calctime(int timetot,int at,int of)
80 {
81         /* FIXME: better distribution */
82         return timetot/of;
83 }
84
85 static struct action {
86         struct action *next;
87         int timetot,stores;
88         unsigned long last_seq;
89         char what[1];
90         } *hashtable[HASH_SIZE];
91 static int hashtable_tot=0;
92
93 static int dumpaction(const struct action *action)
94 {
95 int tot,mins FAKEUSE,hours FAKEUSE,days FAKEUSE,origtot;
96 char *s,fmt[]="%?d";
97
98         if (action) {
99                 tot=(action->timetot+30)/60;
100                 if (doaverage && lifetime_days)
101                         tot/=lifetime_days;
102                 mins=tot; hours=mins/60; days=hours/24;
103                 mins%=60; hours%=24;
104                 }
105         else tot=0;
106         origtot=tot;
107         for (s=formtotal;*s;s++)
108                 switch (*s) {
109                         case '*': case '/': {
110 long l;
111 char *end,*s2;
112
113                                 if (s[1]==*s) { s++; goto dump; }
114                                 for (s2=s+1;isdigit(*s2);s2++);
115                                 l=strtol(s+1,&end,10);
116                                 if (end!=s2) {
117                                         fprintf(ERRH1"Number parse error at column %d of formtotal string!\n",ERRH2,s-formtotal);
118                                         exit(EXIT_FAILURE);
119                                         }
120                                 if (*s=='*') tot*=l;
121                                 else         tot/=l;
122                                 s=s2-1;
123                                 break; }
124                         case ':':
125                                 if (s[1]==*s) { s++; goto dump; }
126                                 if (!isdigit(s[1])) goto dump;
127                                 if (action) {
128                                         fmt[1]=s[1];
129                                         printf(fmt,tot);
130                                         tot=origtot;
131                                         }
132                                 else origtot+=s[1]-'0';
133                                 s+=1;
134                                 break;
135                         default:
136 dump:
137                                 if (action) putchar(*s);
138                                 else origtot++;
139                         }
140         if (action)
141                 printf("=%03d/%02d:%02d %4d\t%s\n",days,hours,mins,
142                         action->stores,action->what);
143         return origtot;
144 }
145
146 #define A (*Ap)
147 #define B (*Bp)
148 #define FUNC(which) \
149         static int sort_##which(const struct action **Ap,const struct action **Bp) \
150         { return (B->which>A->which)-(A->which>B->which); }
151 FUNC(timetot)
152 FUNC(stores)
153 #undef FUNC
154 #undef B
155 #undef A
156
157 static void dumphashtable(void)
158 {
159 int item;
160 struct action *action;
161 struct action **sorta FAKEUSE,**sorti FAKEUSE;
162
163         if (sortby!=SORT_NO) {
164 int totalwidth=dumpaction(NULL);
165
166                 while (totalwidth-->5) putchar(' ');
167                 puts("Total Day Hr Mi Stor\tDescription");
168                 if (!(sorta=malloc(sizeof(*sorta)*hashtable_tot))) {
169                         fprintf(ERRH1"malloc() of %d pointers"ERRNO1,ERRH2,hashtable_tot,ERRNO2);
170                         exit(EXIT_FAILURE);
171                         }
172                 sorti=sorta;
173                 }
174         for (item=0;item<LENGTH(hashtable);item++)
175                 for (action=hashtable[item];action;action=action->next)
176                         if (sortby==SORT_NO)
177                                 dumpaction(action);
178                         else
179                                 *sorti++=action;
180         if (sortby==SORT_NO) return;
181         assert(sorti==sorta+hashtable_tot);
182         qsort(sorta,hashtable_tot,sizeof(*sorta),
183                 (int (*)(const void *,const void *))(sortby==SORT_TIMETOT ? sort_timetot : sort_stores));
184         for (sorti=sorta;sorti<sorta+hashtable_tot;sorti++)
185                 dumpaction(*sorti);
186         free(sorta);
187 }
188
189 static unsigned calchash(const char *s)
190 {
191 unsigned r=57;
192
193         while (*s) r=r*7+11*toupper(*s++);
194         r=r%HASH_SIZE;
195         return r;
196 }
197
198 static void storeone(char *what,int length)
199 {
200 struct action **actionp,*action;
201
202         if (!*what)
203                 return;
204         if (verbose) printf("storeone: %d: %s\n",length,what);
205         for (actionp=hashtable+calchash(what);(action=*actionp);actionp=&action->next)
206                 if (!strcasecmp(action->what,what)) break;
207         if (!action) {
208                 if (!(action=malloc(sizeof(*action)+strlen(what)))) {
209                         fprintf(ERRH1"malloc() for \"%s\""ERRNO1,ERRH2,what,ERRNO2);
210                         exit(EXIT_FAILURE);
211                         }
212                 action->next=NULL;
213                 action->timetot=0;
214                 action->stores=0;
215                 strcpy(action->what,what);
216                 *actionp=action;
217                 hashtable_tot++;
218                 }
219         else {
220                 if (action->last_seq==lifetime_seq) {
221                         if (verbose) puts("storeone: preventing duplicate");
222                         return; /* prevent duplicates like: TV-Music  -->  TV-Fun-Music-Fun */
223                         }
224                 }
225         action->last_seq=lifetime_seq;
226         action->timetot+=length;
227         action->stores++;
228 }
229
230 struct textlist {
231         struct textlist *next;
232         int line;
233         char text[1];
234         };
235 struct textlist *conditions,**conditionstail=&conditions;
236
237 static int iscondition(const char *text)
238 {
239 struct textlist *cond;
240
241         for (cond=conditions;cond;cond=cond->next)
242                 if (!strcasecmp(text,cond->text)) return 1;
243         return 0;
244 }
245
246 static void addlist(struct textlist ***tail,const char *text,int line)
247 {
248 struct textlist *item;
249
250         if (!(item=malloc(sizeof(*item)+strlen(text)))) {
251                 fprintf(ERRH1"malloc() for \"%s\""ERRNO1,ERRH2,text,ERRNO2);
252                 exit(EXIT_FAILURE);
253                 }
254         strcpy(item->text,text);
255         item->next=NULL;
256         **tail=item;
257         *tail=&item->next;
258 }
259
260 static struct textlist *modifies,**modifiestail=&modifies,*modifiescmdl,**modifiescmdltail=&modifiescmdl;
261 static int modifies_tot;
262 static struct modistruct {
263         regex_t regex;
264         char *dst;
265         } *modistructs;
266
267 static void modify_load(void)
268 {
269 static int inited=0;
270 char *finame,*s,*s2;
271 FILE *fi;
272 int line=0,m;
273 struct textlist *item;
274 char buf[LINE_MAX];
275
276         if (inited) return;
277         inited=1;
278         if (asprintf(&finame,"%s"CONFIGFILE,getenv("HOME"))==-1) {
279                 fprintf(ERRH1"Config filename allocation",ERRH2);
280                 exit(EXIT_FAILURE);
281                 }
282         errno=0;
283         if (!(fi=fopen(finame,"rt"))) {
284                 if (errno!=ENOENT)
285                         fprintf(ERRH1"Config file \"%s\" read"ERRNO1,ERRH2,finame,ERRNO2);
286                 return;
287                 }
288
289         while (clearerr(fi),fgets(buf,sizeof(buf),fi)==buf) {
290                 line++;
291                 if ((s=strchr(buf,'\n')) && !s[1]) *s='\0';
292
293                 else {
294                         fprintf(ERRH1"fgets(3) results not newline-terminated"WHERE1,ERRH2,WHERE2);
295                         exit(EXIT_FAILURE);
296                         }
297                 if (!*buf || *buf=='#') {
298 nextline:
299                         continue;
300                         }
301                 if (*buf!='R') {
302                         fprintf(ERRH1"Unrecognized syntax"WHERE1,ERRH2,WHERE2);
303                         exit(EXIT_FAILURE);
304                         }
305                 s=buf+1;
306                 for (;;) {
307 int isplus;
308
309                         while (isspace(*s)) s++;
310                         if (*s==':') break;
311                         if (!isalpha(*s)) {
312                                 fprintf(ERRH1"Invalid character at offset %d"WHERE1,ERRH2,s-buf+1,WHERE2);
313                                 exit(EXIT_FAILURE);
314                                 }
315                         for (s2=s+1;isalpha(*s2);s2++);
316                         if (*s2!='+' && *s2!='-') {
317                                 fprintf(ERRH1"Only plus ('+') or minus ('-'), not '%c' expected at offset %d"WHERE1,ERRH2,*s2,s2-buf+1,WHERE2);
318                                 exit(EXIT_FAILURE);
319                                 }
320                         isplus=(*s2=='+'); *s2++='\0';
321                         if (iscondition(s)!=isplus)
322                                 goto nextline;
323                         s=s2;
324                         }
325                 s++; /* Skip ':' */
326                 addlist(&modifiestail,s,line);
327                 modifies_tot++;
328                 }
329         if (!feof(fi) || ferror(fi))  {
330                 fprintf(ERRH1"fgets(3) \"%s\""ERRNO1,ERRH2,finame,ERRNO2);
331                 exit(EXIT_FAILURE);
332                 }
333         if (fclose(fi))
334                 fprintf(ERRH1"fclose(3) \"%s\""ERRNO1,ERRH2,finame,ERRNO2);
335         *modifiestail=modifiescmdl; /* add all command-line arguments to the end */
336         if (!(modistructs=malloc(sizeof(*modistructs)*modifies_tot))) {
337                 fprintf(ERRH1"malloc() of %d modistructs's"ERRNO1,ERRH2,modifies_tot,ERRNO2);
338                 exit(EXIT_FAILURE);
339                 }
340         for (m=0,item=modifies;m<modifies_tot;m++,item=item->next) {
341 #define line (item->line)
342                 if (!(s=strchr(item->text,'\t'))) {
343                         fprintf(ERRH1"No delimiting tab-character found"WHERE1,ERRH2,WHERE2);
344                         exit(EXIT_FAILURE);
345                         }
346                 *s++='\0'; modistructs[m].dst=s;
347                 if (verbose) printf("regcomp: %s -> %s\n",item->text,s);
348                 if (regcomp(&modistructs[m].regex,item->text,REG_EXTENDED|REG_ICASE)) {
349                         fprintf(ERRH1"regcomp() failed for \"%s\" (%s)"WHERE1,ERRH2,item->text,ERRNO2,WHERE2);
350                         exit(EXIT_FAILURE);
351                         }
352 #undef line
353                 }
354         assert(!item);
355         free(finame);
356 }
357
358 static char *modify(char *what)
359 {
360 regmatch_t matches[10];
361 int i,m;
362 int doprep,willprep;
363 static char modbuf1[sizeof(buf)],modbuf2[sizeof(modbuf1)];
364 char *src=what,*dstbase=modbuf1,*dst=dstbase;
365 const char *start FAKEUSE,*end FAKEUSE,*patt;
366 const struct textlist *item;
367
368         if (verbose) printf("modify: %s\n",what);
369         modify_load();
370         for (m=0,item=modifies,willprep=1;;m++,item=item->next) {
371 enum { PATT_START,PATT_MID,PATT_END,PATT_TERM } pattpos;
372
373                 for (doprep=willprep;doprep>=0;doprep--) {
374                         if (doprep) {
375                                 *dst++='-';
376                                 for (patt=src;;patt++) {
377                                         if (*patt=='-' || !*patt) {
378                                                 if (dst[-1]!='-')
379                                                         *dst++='-';
380                                                 if (!*patt)
381                                                         break;
382                                                 }
383                                         else
384                                                 *dst++=*patt;
385                                         }
386                                 }
387                         else {
388                                 if (!item)
389                                         return src;
390                                 i=regexec(&modistructs[m].regex,src,LENGTH(matches),matches,0);
391                                 if (i==REG_NOMATCH) {
392                                         willprep=0;
393                                         break;
394                                         }
395                                 if (i) {
396                                         fprintf(ERRH1"regexec() failed for \"%s\""ERRNO1,ERRH2,item->text,ERRNO2);
397                                         exit(EXIT_FAILURE);
398                                         }
399                                 willprep=1;
400                                 if (verbose) printf("matched: %s -> %s\n",item->text,modistructs[m].dst);
401                                 pattpos=PATT_START; patt=NULL;
402                                 while (pattpos!=PATT_TERM) {
403                                         switch (pattpos) {
404                                                 case PATT_START:
405                                                         start=src;
406                                                         end=src+matches->rm_so;
407                                                         pattpos=PATT_MID; patt=modistructs[m].dst;
408                                                         break;
409                                                 case PATT_MID:
410                                                         if (!*patt) {
411                                                                 pattpos=PATT_END; patt=NULL;
412                                                                 continue;
413                                                                 }
414                                                         else if (*patt=='@') {
415                                                                 start=src; end=src+strlen(src);
416                                                                 }
417                                                         else if (*patt>='0' && *patt<='9') {
418                 regmatch_t *match=matches+(*patt-'0');
419                                                                 if (match->rm_so==-1
420                                                                  || match->rm_eo==-1) {
421                                                                         fprintf(ERRH1"Trying to substitute '%c' but no \"matches\" entry not set for \"%s\""WHERE1,
422                                                                                         ERRH2,*patt,item->text,WHERE2);
423                                                                         exit(EXIT_FAILURE);
424                                                                         }
425                                                                 if (match->rm_so>match->rm_eo) {
426                                                                         fprintf(ERRH1"Trying to substitute '%c' start>end (%d>%d) for \"%s\""WHERE1,
427                                                                                         ERRH2,*patt,match->rm_so,match->rm_eo,item->text,WHERE2);
428                                                                         exit(EXIT_FAILURE);
429                                                                         }
430                                                                 start=src+match->rm_so; end=src+match->rm_eo;
431                                                                 }
432                                                         else {
433                                                                 start=patt; end=patt+1;
434                                                                 }
435                                                         patt++;
436                                                         break;
437                                                 case PATT_END:
438                                                         start=src+matches->rm_eo;
439                                                         end=src+strlen(src);
440                                                         pattpos=PATT_TERM; /* assumed: patt=NULL; */
441                                                         break;
442                                                 default:
443                                                         assert(0);
444                                                 }
445                                         if ((dst-dstbase+(end-start))>=sizeof(modbuf1)-1/* -1 for '-' during prepping */) {
446                                                 fprintf(ERRH1"Maximum buffer size exceeded during substition for \"%s\""WHERE1,
447                                                                 ERRH2,item->text,WHERE2);
448                                                 exit(EXIT_FAILURE);
449                                                 }
450                                         memcpy(dst,start,end-start);
451                                         dst+=end-start;
452                                         }
453                                 }
454 /* SWAP buffers: */
455                         if (dst==dstbase || (dst==dstbase+1 && *dstbase=='-'))
456                                 return NULL;
457                         *dst='\0';
458                         if (src==what) {
459                                 assert(dstbase==modbuf1);
460                                 src=dstbase;
461                                 dst=dstbase=modbuf2;
462                                 }
463                         else {
464         char *swap;
465                                 assert((src==modbuf1 && dstbase==modbuf2)
466                                                  ||(src==modbuf2 && dstbase==modbuf1));
467                                 swap=src; src=dstbase; dst=dstbase=swap;
468                                 }
469                         } /* for (doprep) */
470                 }
471         /* NOTREACHED */
472 }
473
474 static struct modifycache {
475         struct modifycache *next;
476         char src[1]; /* dst[1] follows after '\0' */
477         } *mcachetable[HASH_SIZE];
478 static unsigned long modifycache_hits;
479
480 static char *modify_cached(char *what)
481 {
482 struct modifycache **mcachep,*mcache;
483 char *dst;
484 size_t whatl;
485
486         if (!*what)
487                 return(NULL);
488         whatl=strlen(what);
489         if (verbose) printf("modify_cached: %s\n",what);
490         for (mcachep=mcachetable+calchash(what);(mcache=*mcachep);mcachep=&mcache->next)
491                 if (!strcasecmp(mcache->src,what)) break;
492         if (!mcache) {
493                 dst=modify(what);
494                 if (!(mcache=malloc(sizeof(*mcache)+whatl+1+(dst?strlen(dst):0)))) {
495                         fprintf(ERRH1"malloc() for \"%s\""ERRNO1,ERRH2,what,ERRNO2);
496                         exit(EXIT_FAILURE);
497                         }
498                 mcache->next=NULL;
499                 memcpy(mcache->src,what,whatl+1);
500                 if (dst)
501                         strcpy(mcache->src+whatl+1,dst);
502                 else
503                         mcache->src[whatl+1]='\0'; /* dst will be empty */
504                 *mcachep=mcache;
505                 }
506         else {
507                 if (verbose) printf("cache hit.\n");
508                 /* if (verbose) would be performance hit */
509                         modifycache_hits++;
510                 }
511         if (!mcache->src[whatl+1])
512                 return(NULL);
513         return(mcache->src+whatl+1);
514 }
515
516 static void modify_cached_stats(void)
517 {
518 struct modifycache **mcachep,*mcache;
519 unsigned long depth,maxdepth=0,entries_total=0;
520 #define MODIFYCACHE_CALLS (modifycache_hits+entries_total)
521
522         for (mcachep=mcachetable;mcachep<mcachetable+HASH_SIZE;mcachep++) {
523                 for (depth=0,mcache=*mcachep;mcache;mcache=mcache->next)
524                         depth++;
525                 if (depth>maxdepth)
526                         maxdepth=depth;
527                 entries_total+=depth;
528                 }
529         printf("modify_cached cache stats: hits=%u.%02u%% (%lu/%lu), HASH_SIZE=%d, maxdepth=%lu\n",
530                 (unsigned)(   100*modifycache_hits/MODIFYCACHE_CALLS     ),
531                 (unsigned)((10000*modifycache_hits/MODIFYCACHE_CALLS)%100),
532                                   modifycache_hits,MODIFYCACHE_CALLS,
533                 HASH_SIZE,maxdepth);
534 #undef MODIFYCACHE_CALLS
535 }
536
537 static void store(char *what,int length)
538 {
539 char ce_trash,*ce,*ceo=&ce_trash;
540
541         if (!(what=modify_cached(what))) {
542                 if (verbose) puts("discarded.");
543                 return;
544                 }
545         if (verbose) printf("store: %d: %s\n",length,what);
546         while ((ce=(tree?strrchr(what,'-'):strchr(what,'-')))) {
547                 if (!tree) *ce='\0';
548                 storeone(what,length);
549                 if (!tree) { *ce='-'; what=ce+1; }
550                 else { *ceo='-'; *(ceo=ce)='\0'; }
551                 }
552         storeone(what,length);
553         if (tree) *ceo='-';
554         lifetime_seq++;
555 }
556
557 static void hit(time_t t,char *bufaction)
558 {
559 static time_t last=-1;
560 static char bufbackup[sizeof(buf)];
561 char *acts[ACTS_MAX],*s;
562 int timetot,acti,i;
563
564         if (verbose) printf("hit: %ld: %s\n",t,bufaction);
565         if (last!=-1) {
566                 if (t<last) {
567                         fprintf(ERRH1"Time goes backward"WHERE1,ERRH2,WHERE2);
568                         t=last;
569                         }
570                 acts[0]=bufbackup;
571                 acti=1;
572                 while ((s=strchr(acts[acti-1],'+'))) {
573                         *s='\0';
574                         acts[acti++]=s+1;
575                         if (acti>=LENGTH(acts)) {
576                                 fprintf(ERRH1"Too many '+'-delimited actions (%d)"WHERE1,ERRH2,acti,WHERE2);
577                                 exit(EXIT_FAILURE);
578                                 }
579                         }
580                 timetot=t-last;
581                 for (i=0;i<acti;i++)
582                         store(acts[i],calctime(timetot,i,acti));
583                 }
584         strcpy(bufbackup,bufaction);
585         last=t;
586 }
587
588 int main(int argc,char **argv)
589 {
590 int optc;
591 time_t basetime=-1,currtime;
592 int hour,min,sec;
593
594         pname=argv[0];
595         while ((optc=getopt_long(argc,argv,"b:pw:qusTtac:f:r:vhV",longopts,NULL))!=EOF) switch (optc) {
596                 
597                 case 'u':
598                         sortby=SORT_NO;
599                         break;
600                 case 's':
601                         sortby=SORT_STORES;
602                         break;
603                 case 'T':
604                         sortby=SORT_TIMETOT;
605                         break;
606                 case 't':
607                         tree=1;
608                         break;
609                 case 'a':
610                         doaverage=1;
611                         break;
612                 case 'c':
613                         if (iscondition(optarg))
614                                 fprintf(ERRH1"Condition \"%s\" already set!\n",ERRH2,optarg);
615                         else addlist(&conditionstail,optarg,-1);
616                         break;
617                 case 'f':
618                         formtotal=optarg;
619                         break;
620                 case 'r': {
621 char *s,*dup;
622
623                         if (!(s=strchr(optarg,':'))) {
624                                 fprintf(ERRH1"No delimiting ':'-character found in -r option \"%s\"!\n",ERRH2,optarg);
625                                 exit(EXIT_FAILURE);
626                                 }
627                         if (!(dup=strdup(optarg))) {
628                                 fprintf(ERRH1"malloc() of \"%s\" string"ERRNO1,ERRH2,optarg,ERRNO2);
629                                 exit(EXIT_FAILURE);
630                                 }
631                         dup[s-optarg]='\t';
632                         addlist(&modifiescmdltail,dup,0);
633                         modifies_tot++;
634                         } break;
635                 case 'v':
636                         verbose=1;
637                         break;
638                 case 'V':
639                         fprintf(stderr,version);
640                         exit(EXIT_FAILURE);
641                 default: /* also 'h' */
642                         usage();
643                         break;
644                 }
645         if (optind==argc) {
646                 if (asprintf(&finame,"%s"DEF_TIMEPLAN,getenv("HOME"))==-1) {
647                         fprintf(ERRH1"Default timeplan filename allocation",ERRH2);
648                         exit(EXIT_FAILURE);
649                         }
650                 }
651         else if (optind+1!=argc) usage();
652         else if (!strcmp(argv[optind],"-")) {
653                 finame="<stdin>";
654                 fi=stdin;
655                 }
656         else finame=argv[optind];
657         if (!fi && !(fi=fopen(finame,"r"))) {
658                 fprintf(ERRH1"open \"%s\" for reading"ERRNO1,ERRH2,finame,ERRNO2);
659                 exit(EXIT_FAILURE);
660                 }
661
662         while (clearerr(fi),fgets(buf,sizeof(buf),fi)==buf) {
663 char *s;
664
665                 line++;
666                 if ((s=strchr(buf,'\n')) && !s[1]) *s='\0';
667                 else {
668                         fprintf(ERRH1"fgets(3) results not newline-terminated"WHERE1,ERRH2,WHERE2);
669                         exit(EXIT_FAILURE);
670                         }
671                 if (!*buf) continue;
672                 if (*buf==':') { /* ":12.7.2000 (St)" */
673 struct tm tm;
674 char wday[3];
675 int i,parsed;
676 time_t t;
677 const char *days[]={"Ne","Po","Ut","St","Ct","Pa","So"};
678
679                         assert(LENGTH(days)==7);
680                         i=sscanf(buf,":%d.%d.%d (%2s)%n",&tm.tm_mday,&tm.tm_mon,&tm.tm_year,wday,&parsed);
681                         if ((i!=4 && i!=5) || parsed!=strlen(buf)) { /* See note in sscanf(3) man page */
682                                 fprintf(ERRH1"Timestamp with incorrect format"WHERE1,ERRH2,WHERE2);
683                                 exit(EXIT_FAILURE);
684                                 }
685                         for (i=0;i<7;i++) if (!strcmp(days[i],wday)) break;
686                         if (i>=7)
687                                 fprintf(ERRH1"Non-parsable week-day name \"%s\""WHERE1,ERRH2,wday,WHERE2);
688                         tm.tm_sec=tm.tm_min=tm.tm_hour=0;
689                         tm.tm_wday=tm.tm_yday=-1;
690                         tm.tm_isdst=0; /* FIXME */
691                         tm.tm_mon--;
692                         tm.tm_year-=1900;
693                         t=mktime(&tm);
694                         if (t==-1 || tm.tm_wday<0 || tm.tm_wday>6
695                             || tm.tm_mday<1 || tm.tm_mday>31
696                                         || tm.tm_mon <1 || tm.tm_mon >12
697                                         || tm.tm_year<80 || tm.tm_year>150
698                                   ) {
699                                 fprintf(ERRH1"Incorrect timestamp \"%s\""WHERE1,ERRH2,buf,WHERE2);
700                                 exit(EXIT_FAILURE);
701                                 }
702                         if (i<7 && tm.tm_wday!=i)
703                                 fprintf(ERRH1"Non-matching week-day, given \"%s\", calculated \"%s\""WHERE1,ERRH2,days[i],days[tm.tm_wday],WHERE2);
704 #define WANTED (60*60*24)
705                         if (basetime!=-1 && basetime+WANTED!=t)
706                                 fprintf(ERRH1"Non-continuous timestamp (%ld, wanted %d) \"%s\""WHERE1,ERRH2,t-basetime,WANTED,buf,WHERE2);
707 #undef WANTED
708                         basetime=t;
709                         store(MARK_DAY,0);
710                         lifetime_days++;
711                         continue;
712                         }
713
714                 if (!(isdigit(buf[0]) && isdigit(buf[1]) && buf[2]==':' && isdigit(buf[3]) && isdigit(buf[4])
715                  && (buf[5]=='-' || (buf[5]==':' && isdigit(buf[6]) && isdigit(buf[7]) && buf[8]=='-'))
716                       )
717                  || (sec=0,sscanf(buf,(buf[5]=='-'?"%d:%d-":"%d:%d:%d-"),&hour,&min,&sec)!=2+(buf[5]==':'))
718                  || hour<0 || hour>23
719                  || min <0 || min >59
720                  || sec <0 || sec >59
721                     ) {
722                         fprintf(ERRH1"Incorrect day-time \"%s\""WHERE1,ERRH2,buf,WHERE2);
723                         exit(EXIT_FAILURE);
724                         }
725                 if (basetime==-1) {
726                         fprintf(ERRH1"Day-time found but no basetime timestamp set"WHERE1,ERRH2,WHERE2);
727                         exit(EXIT_FAILURE);
728                         }
729                 currtime=basetime+(hour*60+min)*60+sec;
730                 hit(currtime,buf+(buf[5]=='-'?6:9));
731                 }
732
733         if (!feof(fi) || ferror(fi))  {
734                 fprintf(ERRH1"fgets(3) \"%s\""ERRNO1,ERRH2,finame,ERRNO2);
735                 exit(EXIT_FAILURE);
736                 }
737         if (fi!=stdin && fclose(fi))
738                 fprintf(ERRH1"fclose(3) \"%s\""ERRNO1,ERRH2,finame,ERRNO2);
739
740         if (verbose)
741                 modify_cached_stats();
742         dumphashtable();
743         return EXIT_SUCCESS;
744 }