-
Notifications
You must be signed in to change notification settings - Fork 2
/
qualcard.c
1724 lines (1544 loc) · 59 KB
/
qualcard.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* qualcard.c Version 1.7 *
* *
* Learn cards by Spaced Repetition Method. *
* This program helps you learn from a set of cards with questions *
* and answers. *
* Copyright (C) 2016-2022+ by Ruben Carlo Benante *
***************************************************************************
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************
* To contact the author, please write to: *
* Ruben Carlo Benante *
* Email: [email protected] *
* Webpage: http://www.beco.cc *
* Phone: +55 (81) 3184-7555 *
***************************************************************************/
/* ---------------------------------------------------------------------- */
/**
* \name GroupUnique
* @{ */
/* @ingroup GroupUnique */
/**
* @file qualcard.c
* @brief Learn cards by Spaced Repetition Method
* @details This program helps you learn from a set of cards with questions and answers
* @version 20160409.000957
* @date 2016-04-09
* @author Ruben Carlo Benante <<[email protected]>>
* @par Webpage
* <<a href="http://www.beco.cc">www.beco.cc</a>>
* @copyright (c) 2016 GNU GPL v2
* @note This program is free software: you can redistribute it
* and/or modify it under the terms of the
* GNU General Public License as published by
* the Free Software Foundation version 2 of the License.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program.
* If not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA. 02111-1307, USA.
* Or read it online at <<http://www.gnu.org/licenses/>>.
*
*
* @todo Now that you have the template, hands on! Programme!
* @warning Be carefull not to lose your mind in small things.
* @bug This file right now does nothing usefull
*
*/
/* ---------------------------------------------------------------------- */
/* includes */
#include <stdio.h> /* Standard I/O functions */
#include <stdlib.h> /* Miscellaneous functions (rand, malloc, srand)*/
#include <getopt.h> /* get options from system argc/argv */
#include <time.h> /* Time and date functions */
#include <string.h> /* Strings functions definitions */
#include <dirent.h> /* Defines directory entries */
#include <assert.h> /* Verify assumptions with assert */
#include <unistd.h> /* UNIX standard function */
#include <sys/stat.h> /* File status and information */
#include <errno.h> /* Error number codes errno */
#include <math.h> /* Math functions */
/* ---------------------------------------------------------------------- */
/* definitions */
/* #define BUILD (20160409.000957) / * * < Build Version Number */
#define EXTDB ".ex4" /**< Database extension: theme-question-answer.ex4 (example: english-word-definition.ex4) */
#define EXTCF ".cf4" /**< History file extension: user-qualcard.cf4 */
#define CFGINI "qualcard.ini" /*<< Configuration file */
#define SCOREA 4.92
#define SCOREB 3.90
#define SCOREC 3.05
#define SCORED 2.20
#define SCOREE 1.35
#define SCOREF 0.60
#define TMEM 0 /**< tencards memory index */
#define TFIL 1 /**< tencards file index (card number) */
#define TEND -2 /**< tencards end of list */
#define TVAL -1 /* not in memory, but valid new card from file */
/* randnorep() input: mode */
#define DRAWBASKET -1 /**< MODE set randnorep() to draw a item from the basket */
#define LISTBASKET -2 /**< MODE set randnorep() to list itens in the basket */
#define REMOVEBASKET -3 /**< MODE set randnorep() to remove a specific item from basket */
#define FILLBASKET -4 /**< MODE set randnorep() to fill basket with new numbers */
/* randnorep() output: error codes returned */
#define BASKETOK 0 /**< randnorep() return code for no error */
#define BASKETEMPTY -1 /**< randnorep() return code for empty list */
#define BASKETLISTED -2 /**< randnorep() return code for all listed */
#define BASKETERROR -3 /**< randnorep() return code for other error */
#define BASKETFULL -4 /**< randnorep() return code for full basket */
/* Debug */
#ifndef DEBUG /* gcc -DDEBUG=1 */
#define DEBUG 0 /**< Activate/deactivate debug mode */
#endif
/** @brief Debug message if DEBUG on */
#define IFDEBUG(M) if(DEBUG) fprintf(stderr, "[DEBUG file:%s line:%d]: " M "\n", __FILE__, __LINE__); else {;}
/* limits */
#define STRSIZE 1500 /**< String buffer size */
#define STROPT 100 /**< String size for options INI */
#define SOPT 4 /* opt string '99\n\0' */
#define PATHSIZE 1600 /**< Maximum $PATH size */
#define DTSIZE 9 /**< String with yyyymmdd */
#define PEREXEC 10 /**< How many cards presented per round (execution) */
#define NEWEXEC 1 /**< Minimum number of new cards presented per round */
/* ---------------------------------------------------------------------- */
/* globals */
static int verb = 0; /**< verbose level, global within the file */
static int SUMMA = 0; /**< print summary only and exit */
static int DBNUM = 0; /**< pick a database (ex4) by number from command line */
typedef struct scfg /* configuration data struct */
{
int QTDCARD; /* database size */
int today; /* yyyymmdd */
time_t tstart; /* start time (s) of this session */
double session; /* duration of all session (s) */
char dbpath[PATHSIZE]; /* path to commom database directory */
char cfgrealpath[PATHSIZE]; /* path to own config directory with config (ini), history (cf4) and databases (ex4), read and write */
char cfguserpath[PATHSIZE]; /* path to some other user config directory (just for read) */
char pathuser[STRSIZE]; /* pathuser/.config another user name account for read only */
char fileuser[STRSIZE]; /* fileuser-theme-question-answer.cf4 history file for username currently practicing */
char realuser[STRSIZE]; /* user name of the account */
char dbasef[STRSIZE], configwf[STRSIZE]; /* current filenames: database (ex4) and configuration (cf4) */
int *cfcard, *cfdate; /* card num, last date */
double *cfave; /* card average */
int cfsize; /* size of config file, number of cards */
char **dbfiles; /* char dbfiles[number of ex4 files][string lenght of the biggest];*/
int dbfsize; /* number of database ex4 files */
int invert; /* if true, print first the back, then the front of the card */
int option[2]; /* [0]:order=[0:sort, 1:random], [1]:score=[0:after, 1:before] */
} tcfg; /* configuration data type */
/* ---------------------------------------------------------------------- */
/* prototypes */
void help(void); /* print some help */
void copyr(void); /* print version and copyright information */
void qualcard_init(tcfg *cfg); /* global initialization function */
void summary(tcfg c); /* how many cards to review */
double randmm(double min, double max); /* drawn a number from [min, max[ */
int ave2day(double ave); /* given an average, return how many days */
int newdate(int oldd, int days); /* add days to a date */
char *prettydate(int somedate); /* return date in a pretty format */
void readcfg(tcfg *c); /* read config file */
void *reallocordie(void *ptr, size_t sz); /* resize the memory block of a pointer or die */
void readdbfiles(tcfg *c); /* read files from directory and create a dynamic vector of strings */
char *theme(char *file); /* take the theme from a database file name */
int newcard(tcfg c, int tencards[10][2]); /* drawn a new card */
void select10cards(tcfg *c, int tencards[10][2]); /* select 10 cards (old or new) to be presented */
void sortmemo(tcfg *c); /* prioritary (old) comes first (selection sort) */
void getcard(char *dbfile, int cardnum, char *cardfr, char *cardbk); /* given a card number, get it from file */
void cardfaces(char *card, char *fr, char *bk); /* get card faces front/back */
void save2memo(tcfg *c, int i, int card, double scor); /* save new or update old card */
void save2file(tcfg c); /* save updated cards in memory to config file */
int dbsize(char *dbname); /* database ex4 size */
void cfanalyses(char *sumfile, int today, int qtd, int *view, int *learn, double *pct, double *addscore, int *ncardl); /* analyses a history file */
void createcfgdir(tcfg *c); /* creates /home/user/.config/qualcard/ */
char *filenopath(char *filepath); /* get filename with no path */
int randnorep(int mode, int *n); /* drawn numbers from a list with no repetition */
void changebarnet(char *s); /* change \n and \t to the real thing */
void changecolon(char *nt); /* change char 254 back to a colon sign */
int diffdays(int newd, int oldd); /* Difference of two dates in days. Positive if new>old, 0 if equals, negative c.c. */
double score(double ave, int late); /* return the new score when the revision is late */
void menudb(tcfg *c); /* read menu */
char *dbcore(char *s); /* grab the core name of the file */
void sessiontime(tcfg *c); /* calculates duration of this session and accumulated time */
double getactime(FILE *fp); /* read time if exists. points to first card stat */
void sstrip(char *s); /* remove \n \t and double spaces from string */
void setoption(int optini[2], char *optarg); /* read option from command line and update vector of options in memory */
void readini(tcfg *c); /* read INI file options */
void cmpoption(tcfg *c, int mopt[2]); /* compare command line options with INI file and save if necessary */
/* ---------------------------------------------------------------------- */
/* @ingroup GroupUnique */
/**
* @brief Main function, loops the cards, save and exit
* @details Ladies and Gentleman... It's tiiiime!
* Fightiiiiing at the blue corner,
* he, who has compiled more C code than any other adversary in the history,
* he, who has developed UNIX and Linux, and is an inspiration to maaany languages
* and compilers, the GNU C Compiler, GCC!
* Fightiiiiing at the red corner, the challenger, in his first fight, lacking of any
* valid experience but angrily, blindly, and no doubtfully, will try to
* compile this program without errors. He, the student, the apprentice,
* the developer, beco!!
*
* @param[in] argc Argument counter
* @param[in] argv Argument strings (argument values)
*
* @retval 0 If succeed (EXIT_SUCCESS).
* @retval 1 Or another error code if failed.
*
* @par Example
* @code
* $./qualcard -h
* @endcode
*
* @warning Be carefull with...
* @bug There is a bug with...
* @todo Need to do...
* @note You can read more about it at <<a href="http://www.beco.cc">www.beco.cc</a>>
* @author Ruben Carlo Benante
* @version 20160409.000957
* @date 2016-04-09
*
*/
int main(int argc, char *argv[])
{
char sopt[SOPT]; /* string opt */
char *p; /* strchr remove \n from sopt */
int opt; /* return from getopt() and user options */
tcfg c = {0}; /* struct to configuration variables */
int i; /* index, auxiliary */
int newd; /* new date after adding up day's equivalent score */
int futd; /* future revision date after presenting today */
int tencards[10][2]; /* ten cards, index in memory (-1 if new), line in file */
int again = 1; /* while some card score presented is still zero */
int repet[10] = {0}; /* which card repeated how many times */
double sco, oldsco; /* the score to a card */
char cardfr[STRSIZE], cardbk[STRSIZE]; /* card front and back */
int memopt[2] = {-1, -1}; /* options in memory to compare to INI file */
IFDEBUG("Starting optarg loop...\n");
/* getopt() configured options:
* -h Help.
* -c Copyright & version.
* -v Increase verbose.
* -q Quiet, decrease verbose.
* -s Status of all database reviews. Together with -n N shows only the
* status of a single chosen database.
* -u username Set the player name (default: whoami).
* -p username Set the username for config path (together with -s only).
* -d database Set the database to use (default: ask).
* -n N Pick a database number N from command line. With -s, print status of
* that specific database.
* -i Invert presentation order (first the back, then the front of the card).
*
* -e OPTION=VALUE Set OPTION. Options are: order=[sort|random], score=[before|after]
* Example: qualcard -e order=sort -e score=after
* Options are saved into ~/.config/qualcard/qualcard.ini
*/
opterr = 0;
while((opt = getopt(argc, argv, "hcvqsp:u:d:in:e:")) != EOF)
switch(opt)
{
case 'h': /* help and exit */
help();
break;
case 'c': /* copyright and exit */
copyr();
break;
case 'v': /* verbose */
verb++;
break;
case 'q': /* quiet */
verb--;
break;
case 's': /* summary */
SUMMA = 1;
break;
case 'u': /* username */
strncpy(c.fileuser, optarg, STRSIZE);
break;
case 'p': /* username for other account (path) */
strncpy(c.pathuser, optarg, STRSIZE);
break;
case 'i': /* invert */
c.invert = 1;
break;
case 'd': /* database */
strncpy(c.dbasef, optarg, STRSIZE);
break;
case 'n': /* database number */
DBNUM = strtol(optarg, NULL, 10);
if(DBNUM == 0)
{
help();
printf("\nError: wrong database number on arg -n N\n");
/* exit(EXIT_FAILURE); */
}
break;
case 'e': /* options -e order=sort/random -e score=after/before */
setoption(memopt, optarg); /* read option from command line and update vector of options in memory */
break;
case '?': /* wrong option, exit */
default:
printf("Type\n\t$man %s\nor\n\t$%s -h\nfor help.\n\n", argv[0], argv[0]);
return EXIT_FAILURE;
}
if(verb >= 0)
{
printf("QualCard v.%s - Spaced Repetition", VERSION);
if(verb > 0)
printf(", by Dr. Beco");
printf("\n");
}
if(verb > 1)
printf("Verbose level set at: %d\n", verb);
if(c.pathuser[0] != '\0' && SUMMA != 1)
{
if(verb > 1)
printf("Option -p must be used with -s. Setting -s forcefully. Use -h for help.\n");
SUMMA = 1;
}
qualcard_init(&c); /* initialization function */
cmpoption(&c, memopt); /* compare command line options with INI file and save if necessary */
if(DBNUM != 0)
{
if(verb > 1)
printf("Used option: -n %d\n", DBNUM);
if(DBNUM < 1 || DBNUM > c.dbfsize)
{
printf("Database %d not found!\n", DBNUM);
exit(EXIT_FAILURE);
}
}
summary(c); /* how many cards to review */
if(SUMMA)
exit(EXIT_SUCCESS);
/* TODO: read dbasef from system databases with:
* -d english
*/
menudb(&c);
if(verb > 2)
{
printf("\nDataBase file: %s (%d cards)\n", filenopath(c.dbasef), c.QTDCARD);
printf("History file: %s\n", filenopath(c.configwf));
}
readcfg(&c); /* read card stats from chosen dbfile */
select10cards(&c, tencards);
printf("\n");
while(again)
{
again = 0;
for(i = 0; i < 10; i++)
{
if(tencards[i][TMEM] == TEND) /* already presented and ok */
continue;
getcard(c.dbasef, tencards[i][TFIL], cardfr, cardbk);
printf("-----------------------------------------------------------\n");
if(TVAL == tencards[i][TMEM]) /* new card? */
{
printf("Card %d (new card for today)\n\n", tencards[i][TFIL] + 1);
oldsco = 0.0;
}
else
{
oldsco = c.cfave[tencards[i][TMEM]];
newd = newdate(c.cfdate[tencards[i][TMEM]], ave2day(oldsco));
printf("Card %d (revision date %s)\n\n", tencards[i][TFIL] + 1, prettydate(newd));
}
if(c.invert)
printf("%s\n", cardbk); /* fgets already get one \n */
else
printf("%s\n\n", cardfr);
printf("---------------Press <ENTER> to turn the card--------------\n");
do opt = getchar();
while(opt != '\n');
if(c.invert)
printf("%s\n\n", cardfr);
else
printf("%s\n", cardbk); /* fgets already get one \n */
do
{
if(c.option[1]==0) /* INI score=after */
printf("Your self-evaluation (from 0 to 5, default 0) is: ");
else /* INI score=before */
printf("Current score: %.1f Self-evaluation ([0] ... 5): ", oldsco);
/* scanf("%d%*c", &opt); /1* discard the '\n'. Better use fgets() *1/ */
fgets(sopt, SOPT, stdin);
if((p = strchr(sopt, '\n'))) * p = '\0';
if(sopt[0] == '\0') /* pressing <enter> means evaluating to 0 */
{
opt = 0;
break;
}
opt = strtol(sopt, NULL, 10);
}
while(opt < 0 || opt > 5);
if(!opt)
{
repet[i]++;
again = 1;
}
else
{
if(repet[i])
sco = (double)opt / ((double)repet[i] + 1.0);
else
sco = (double)opt;
save2memo(&c, tencards[i][TMEM], tencards[i][TFIL], sco);
if(tencards[i][TMEM] == TVAL)
tencards[i][TMEM] = c.cfsize - 1;
futd = newdate(c.today, ave2day(c.cfave[tencards[i][TMEM]]));
if(c.option[1]==0) /* INI score=after */
printf("Old score: %.1f, new score: %.1f, revision set to %s\n", oldsco, c.cfave[tencards[i][TMEM]], prettydate(futd));
else /* INI score=before */
printf("New score: %.1f Revision set to %s\n", c.cfave[tencards[i][TMEM]], prettydate(futd));
tencards[i][TMEM] = TEND; /* presented and ok */
}
} /* for i < 10 cards */
} /* while(again) */
printf("-----------------------------------------------------------\n");
sessiontime(&c); /* calculates duration of this session and accumulated time */
save2file(c);
printf("\nLive as if you were to die tomorrow.\nLearn as if you were to live forever. (Mahatma Gandhi)\n");
printf("Thank you for using QualCard version %s.\n\n", VERSION);
return EXIT_SUCCESS;
}
/* save new or update old card */
void save2memo(tcfg *c, int i, int card, double scor)
{
if(-1 == i) /* no index implies new memory block */
{
c->cfsize++;
c->cfcard = (int *)reallocordie(c->cfcard, sizeof(int) * c->cfsize);
c->cfdate = (int *)reallocordie(c->cfdate, sizeof(int) * c->cfsize);
c->cfave = (double *)reallocordie(c->cfave, sizeof(double) * c->cfsize);
c->cfcard[c->cfsize - 1] = card;
c->cfdate[c->cfsize - 1] = c->today;
c->cfave[c->cfsize - 1] = scor / 1.3; /* first score -23.07% */
return;
}
assert(c->cfcard[i] == card); /* if c->cfcard[i] != card; then error; */
c->cfdate[i] = c->today;
c->cfave[i] = (c->cfave[i] + scor) / 2.0;
return;
}
/* save updated cards in memory to config file */
/* file format cf4:
* session time (double)
* card number (int) card last date (int) card grade average (double)
* ...
*/
void save2file(tcfg c)
{
int i;
FILE *fp;
if((fp = fopen(c.configwf, "w")) != NULL) /* create from scratch */
{
fprintf(fp, "%lf\n", c.session); /* accumulated time */
for(i = 0; i < c.cfsize; i++)
fprintf(fp, "%5d %8d %6.4f\n", c.cfcard[i], c.cfdate[i], c.cfave[i]);
fclose(fp);
}
else /* /home/carol/.config/qualcard/carol-ls-key-description.cf4 */
fprintf(stderr, "save2file(): can't open config file %s for writing.\n", c.configwf);
return;
}
/* read option from string and update vector of options */
/* options -e order=sort/random -e score=after/before */
void setoption(int vopt[2], char *sopt)
{
char *p = NULL;
char option[STROPT];
char value[STROPT];
int o = -1, v = -1; /* option and value indexes */
strncpy(option, sopt, STROPT);
/* printf("setoption option='%s'\n", option); */
if((p = strchr(option, '\n')) != NULL)
* p = '\0';
if((p = strchr(option, '=')) == NULL)
return;
*p = '\0';
if(!strncmp(option, "order", STROPT))
o = 0;
if(!strncmp(option, "score", STROPT))
o = 1;
if(o == -1)
return;
strncpy(value, p + 1, STROPT);
/* printf("setoption value='%s'\n", value); */
if(o == 0)
{
if(!strncmp(value, "sort", STROPT))
v = 0;
if(!strncmp(value, "random", STROPT))
v = 1;
}
if(o == 1)
{
if(!strncmp(value, "after", STROPT))
v = 0;
if(!strncmp(value, "before", STROPT))
v = 1;
}
if(v == -1)
return;
vopt[o] = v;
return;
}
/* compare command line options with INI file and save if necessary */
void cmpoption(tcfg *c, int mopt[2])
{
int o;
int fs = 0; /* flag save is necessary */
char filename[STRSIZE];
FILE *fp;
for(o = 0; o < 2; o++)
{
if(mopt[o] == -1)
continue;
if(c->option[o] == mopt[o])
continue;
fs = 1;
c->option[o] = mopt[o];
}
if(verb > 1)
{
printf("INI option order=%s\n", c->option[0] ? "random" : "sort");
printf("INI option score=%s\n", c->option[1] ? "before" : "after");
}
if(fs) /* saving ini file */
{
snprintf(filename, STRSIZE, "%s/%s", c->cfgrealpath, CFGINI);
if((fp = fopen(filename, "w")) != NULL) /* lets save a ini file! */
{
fprintf(fp, "# Qualcard Initialization File\n");
fprintf(fp, "# 2021-11-15 (C) by Ruben Carlo Benante\n");
fprintf(fp, "#\n");
fprintf(fp, "# Usage:\n");
fprintf(fp, "# option=value\n");
fprintf(fp, "#\n");
fprintf(fp, "# Options available:\n");
fprintf(fp, "#\n");
fprintf(fp, "# order=[sort|random]\n");
fprintf(fp, "# sort : select cards on due date (default)\n");
fprintf(fp, "# random : select random cards to practice\n");
fprintf(fp, "#\n");
fprintf(fp, "# score=[after|before]\n");
fprintf(fp, "# after : show old score only after asking your self-evaluation (default)\n");
fprintf(fp, "# before : show score before asking your self-evaluation\n");
fprintf(fp, "\n");
fprintf(fp, "order=%s\n", c->option[0] ? "random" : "sort");
fprintf(fp, "score=%s\n", c->option[1] ? "before" : "after");
fprintf(fp, "\n");
fclose(fp);
}
else
fprintf(stderr, "Can't save INI file.\n");
}
}
/* get card faces */
void cardfaces(char *card, char *fr, char *bk)
{
char *colon;
strncpy(fr, card, STRSIZE);
changebarnet(fr);
strncpy(bk, fr, STRSIZE); /* default in case of problem: back == front */
colon = fr;
while(1)
{
colon = strchr(colon, ':');
if(!colon)
{
fprintf(stderr, "\n------------------------------------------\n");
fprintf(stderr, "Wrong card without '::' separator.\n%s\n", card);
changecolon(fr); /* change char 254 back to a colon sign */
changecolon(bk); /* change char 254 back to a colon sign */
return; /* not found, return all card to front and back */
}
colon++;
if(*colon == ':') /* found :: */
break;
}
*(colon - 1) = '\0'; /* front */
strncpy(bk, colon + 1, STRSIZE); /* back */
changecolon(fr); /* change char 254 back to a colon sign */
changecolon(bk); /* change char 254 back to a colon sign */
return;
}
/* change char 254 back to a colon sign */
void changecolon(char *nt)
{
do
if((nt = strchr(nt, 254)))
* nt = ':';
while(nt != NULL);
}
/* change '\n', '\t' and '\\' to the real thing */
void changebarnet(char *nt)
{
do
if((nt = strchr(nt, '\\')))
switch(*++nt)
{
case 'n': /* \n becomes space+\n */
*nt = '\n';
goto space;
case 't': /* \t becomes space+\t */
*nt = '\t';
goto space;
case ':': /* : becomes space + þ 254 */
*nt = 254;
goto space;
space:
case '\\': /* \\ becomes space+\ */
*(nt - 1) = ' ';
nt++;
}
while(nt != NULL);
}
/* get filename with no path */
char *filenopath(char *filepath)
{
static char filename[STRSIZE];
char *bar;
strncpy(filename, filepath, STRSIZE);
if((bar = strrchr(filepath, '/'))) /* find the last / */
{
bar++; /* next char starts the filename */
strncpy(filename, bar, STRSIZE);
}
/* else /1* no bar? that's odd... *1/ */
/* { */
/* fprintf(stderr, "Filename %s must be an absolute path.\n", filepath); */
/* exit(EXIT_FAILURE); */
/* } */
return filename;
}
/* prioritary (older) comes first (selection sort) */
void sortmemo(tcfg *c)
{
int i, j, iux;
double ki, kj, fux;
if(c->cfsize < 2)
return;
for(i = 0; i < c->cfsize - 1; i++)
for(j = i + 1; j < c->cfsize; j++)
{
ki = newdate(c->cfdate[i], ave2day(c->cfave[i])) + c->cfave[i] / 10.0;
kj = newdate(c->cfdate[j], ave2day(c->cfave[j])) + c->cfave[j] / 10.0;
if(ki > kj) /* ki is after, invert */
{
/* if(ki == kj && c->cfave[i] <= c->cfave[j]) /1* 1st score is lower, do not swap *1/ */
/* continue; */
/* swap cards number */
iux = c->cfcard[i];
c->cfcard[i] = c->cfcard[j];
c->cfcard[j] = iux;
/* swap cards presented date */
iux = c->cfdate[i];
c->cfdate[i] = c->cfdate[j];
c->cfdate[j] = iux;
/* swap cards average */
fux = c->cfave[i];
c->cfave[i] = c->cfave[j];
c->cfave[j] = fux;
}
}
}
/* select 10 cards (old or new) to be presented */
void select10cards(tcfg *c, int tencards[10][2])
{
int i, j;
for(i = 0; i < 10; i++) /* zeroing */
tencards[i][TMEM] = tencards[i][TFIL] = TEND; /* end of cards */
sortmemo(c); /* sort cfcard, cfdate and cfave, by date+days(ave) */
for(i = 0; i < 9 && i < c->cfsize; i++) /* nine olds if possible */
{
if(newdate(c->cfdate[i], ave2day(c->cfave[i])) > c->today) /* just until today */
break;
tencards[i][TMEM] = i; /* take the first nine or less */
tencards[i][TFIL] = c->cfcard[i]; /* file line */
}
for(j = i; j < 10; j++)
{
/* new not in memory nor in tencards already */
if((tencards[j][TFIL] = newcard(*c, tencards)) == TEND)
break; /* there is not enough */
tencards[j][TMEM] = TVAL; /* not in memory, but valid new card from file */
}
if(j < 10) /* still need, lets see cards for tomorrow */
{
while(i < c->cfsize && j < 10)
{
tencards[j][TMEM] = i; /* take the next waiting in history */
tencards[j][TFIL] = c->cfcard[i]; /* file line */
i++;
j++;
}
}
}
/* database ex4 size, number of lines = QTDCARD */
int dbsize(char *dbname)
{
char line[STRSIZE];
int qtdl = 0;
FILE *fp;
if(!(fp = fopen(dbname, "r")))
{
fprintf(stderr, "Fail to open database %s.\n", dbname);
exit(EXIT_FAILURE);
}
do
{
fgets(line, STRSIZE, fp);
qtdl++;
}
while(!feof(fp));
fclose(fp);
return --qtdl;
}
/* read time if exists. points to first card stat */
double getactime(FILE *fp)
{
int card, date;
double ave;
double ac = 0.0;
errno = 0;
fseek(fp, 0, 0);
if(3 == fscanf(fp, "%d %d %lf\n", &card, &date, &ave))
{
fseek(fp, 0, 0);
errno = ENODATA;
return 0.0; /* old file format, no accumulated time */
}
fseek(fp, 0, 0);
if(1 == fscanf(fp, "%lf\n", &ac)) /* read first line of accumulated time */
return ac; /* let it point to the second line and return */
errno = EPROTO;
perror("some strange error\n");
fseek(fp, 0, 0);
return 0.0; /* no accumulated time */
}
/* history analises */
void cfanalyses(char *sumfile, int today, int qtd, int *view, int *learn, double *pct, double *addscore, int *ncardl)
{
int card, date, revd; /* card number, card date last seen, card review date */
int late; /* days late */
double ave; /* average of a single card written in disk */
FILE *fp;
int alla = 1; /* all cards are A */
*view = 0; /* number of cards viewed from the total */
*learn = 0; /* number of cards with score greater than SCOREA */
*pct = 0.0; /* percentage of completeness decays with time */
*addscore = 0.0; /* just the scores of cards seen */
*ncardl = 0; /* number of cards late that need review */
if(!(fp = fopen(sumfile, "r"))) /* temporary configwf in a loop */
return;
ave = getactime(fp); /* ignore accumulated time if it exists */
while(3 == fscanf(fp, "%d %d %lf\n", &card, &date, &ave))
{
(*view)++;
*addscore += ave;
if(ave >= SCOREB)
(*learn)++;
if(ave < SCOREA)
alla = 0; /* not all cards are A */
revd = newdate(date, ave2day(ave));
late = 0;
if(today - revd >= 0) /* late or due today */
{
late = diffdays(today, revd);
(*ncardl)++;
}
*pct += score(ave, late); /* late is positive or zero */
}
fclose(fp);
*pct /= ((double)qtd);
if(*pct > SCOREA && alla) /* it is not impossible to achieve 100% */
*pct = 5.0;
*pct *= 20.0; /* 0%..100% */
if(*view == 0)
*addscore = 0.0;
else
*addscore /= ((double) * view); /* average of scores you've got so far */
if(*addscore > SCOREA && alla) /* it is not impossible to achieve 5.0 */
*addscore = 5.0;
return;
}
/* return the new score when the revision is late */
double score(double ave, int late)
{
if(late == 1 && ave > SCOREA) /* don't let one day spoil the fun */
return SCOREA + 0.01;
ave -= ((double)late / 3.5);
if(ave < 0.0)
ave = 0.0;
return ave;
}
/* calculates duration of this session and accumulated time */
void sessiontime(tcfg *c)
{
double fsec; /* seconds */
time_t ttnow;
int h0, m0, s0, h1, m1, s1;
ttnow = time(NULL);
fsec = difftime(ttnow, c->tstart); /* this session's duration in seconds */
c->session += fsec; /* all sessions in seconds */
h0 = (int)fsec / 3600;
m0 = (int)(((fsec / 3600.0) - ((int)fsec / 3600)) * 60.0);
s0 = (int)(((fsec / 60.0) - ((int)(h0 * 60 + m0))) * 60.0);
h1 = (int)c->session / 3600;
m1 = (int)(((c->session / 3600.0) - ((int)c->session / 3600)) * 60.0);
s1 = (int)(((c->session / 60.0) - ((int)(h1 * 60 + m1))) * 60.0);
/* printf("end=%.2lf, start=%.2lf, diff=%.2lf, sessionn=%.2lf\n", (double)ttnow, (double)c->tstart, fsec, c->session); */
printf("This session: %02d:%02d:%02d. Accumulated time: %02d:%02d:%02d\n", h0, m0, s0, h1, m1, s1);
return;
}
/* Difference of two dates in days. Positive if new>old, 0 if equals, negative c.c. */
int diffdays(int newd, int oldd)
{
int ano, mes, dia;//, aux;
double fsec; /* seconds */
time_t ttnew, ttold; /* epochs */
struct tm tmnew = {0}, tmold = {0}; /* date fields */
ano = oldd / 10000;
oldd -= ano * 10000;
mes = oldd / 100;
oldd -= mes * 100;
dia = oldd;
tmold.tm_year = ano - 1900;
tmold.tm_mon = mes - 1;
tmold.tm_mday = dia;
ttold = mktime(&tmold);
ano = newd / 10000;
newd -= ano * 10000;
mes = newd / 100;
newd -= mes * 100;
dia = newd;
tmnew.tm_year = ano - 1900;
tmnew.tm_mon = mes - 1;
tmnew.tm_mday = dia;
ttnew = mktime(&tmnew);
fsec = difftime(ttnew, ttold); /* difference in seconds */
dia = fsec / 86400.0; /* difference in days */
return dia;
}
/* ---------------------------------------------------------------------- */
/**
* @ingroup GroupUnique
* @brief Prints the summary and exit
* @details Prints how many cards to review in each database
* @return Void
* @author Ruben Carlo Benante
* @version 20160409.000957
* @date 2016-04-09
* @todo This function is not ready
*
*/
void summary(tcfg c)
{
int i, view = 0, learn = 0, qtd = 0;
char *dbc;
double pview, plearn; /* percentages */
double ave; /* average 0...5 of cards you've seen in a database */
double pct; /* percentage of your achievements, decay with time */
int clate; /* number of cards late */
int maxlen = 14, len;
char summaryf[PATHSIZE];
char cardfr[STRSIZE], cardbk[STRSIZE]; /* card front and back */
for(i = 0; i < c.dbfsize; i++) /* database file list */
if((len = strlen(theme(filenopath(c.dbfiles[i])))) > maxlen)
maxlen = len;
maxlen++; /* 15 or more */
/* | N | Database | Comp.% | Total| Viewed (%) | Learned (%) | Review | Score | */
printf("| N | %-*s | %6s |%6s | %13s | %13s | %5s | %5s |\n", maxlen, "Database", "Comp.%", "Total", "Viewed (%)", "Learned (%)", "Review", "Score");
for(i = 0; i < c.dbfsize; i++) /* database file list */
{
if(DBNUM && DBNUM - 1 != i)
continue;
qtd = dbsize(c.dbfiles[i]);
dbc = dbcore(c.dbfiles[i]);
if(strlen(c.cfguserpath) + strlen(c.fileuser) + strlen(dbc) + strlen(EXTCF) >= PATHSIZE)
{
fprintf(stderr, "Summary filename overflow\n");
exit(EXIT_FAILURE);
}
snprintf(summaryf, PATHSIZE, "%s/%s-%s%s", c.cfguserpath, c.fileuser, dbc, EXTCF);
cfanalyses(summaryf, c.today, qtd, &view, &learn, &pct, &ave, &clate);
pview = ((double)view / (double)qtd) * 100.0;
plearn = ((double)learn / (double)qtd) * 100.0;
printf("| %2d | %-*s | %5.1f%% | %5d | %4d (%5.1f%%) | %4d (%5.1f%%) | %6d | %5.1f |\n", i + 1, maxlen, theme(filenopath(c.dbfiles[i])), pct, qtd, view, pview, learn, plearn, clate, ave);
}
if(SUMMA && DBNUM)
{
printf("List of cards, revision and scores:\n");
menudb(&c);
readcfg(&c);
for(i = 0; i < c.cfsize; i++) /* entries in history file cf4 */
{
getcard(c.dbasef, c.cfcard[i], cardfr, cardbk);
sstrip(cardfr);
sstrip(cardbk);
/* printf("debug revisao %d score: %lf --", c.cfdate[i], c.cfave[i]); */
printf("Card: %4d Revision: %s Score: %.4lf Brief: %.9s :: %.9s\n", c.cfcard[i] + 1, prettydate(newdate(c.cfdate[i], ave2day(c.cfave[i]))), c.cfave[i], cardfr, cardbk);
}
}