summaryrefslogtreecommitdiffstats
path: root/fcomp.c
blob: bff6823d4ee6e86d40af1d40a722dff1eee602df (plain) (blame)
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
/**
 * fcomp - parse text for string tokens and search for them
 * Copyright (C) 2019  Anastasis Grammenos
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "getopt.h"
#include "unistd.h"
#include "ctype.h"
#include "linenoise.h"

static const char valid[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                              'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                              'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                              'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                              'W', 'X', 'Y', 'Z', '-', '_', '0', '1', '2', '3', '4', '5',
                              '6', '7', '8', '9' };

typedef struct slist {
    char **s;
    unsigned int n;
} slist;

typedef struct token {
    char *s;
    unsigned int count;
} token;

/**
 * Count result */
typedef struct result {
    token **tok;
    unsigned int n;
} result;

/**
 * search methods */
static int exact(const char *str, const char *c);
static int starts(const char *str, const char *c);
static int fuz(const char *str, const char *c);

/**
 * stats for debugging */
typedef struct stats {
    unsigned int discarded;
    char *search_results;
    char *tok_results;
    char *unique_results;
} stats;

static stats st = {
    0,
    NULL,
    NULL,
    NULL
};

/**
 * config */
typedef struct config {
    int help; /** 0: off 1: on */
    int debug; /** 0: off 1: on */
    int stats; /** 0: off 1: on */
    int stdin; /** 0: off 1: on */
    int reverse_sort; /** 0: off 1: on */
    int lisp_print; /** 0: off 1: on */
    int print_count; /** 0: off 1: on */
    int print_all; /** 0: off 1: on */
    int all_uniq; /** 0: off 1: on */
    int interactive; /** 0: off 1: on */
    int prompt;	/** 0: off 1: on */
    int filestream; /** 0: off 1: on */
    char *file;
    char *query;
    unsigned int min_word_size;
    int evc; /** 0: off 1: on */
    char *extra_valid_chars;
    int eic; /** 0: off 1: on */
    char *extra_invalid_chars;
    int (*search_method)(const char *, const char *);
    unsigned int max_token_size;
} config;

/**
 * Initial config vector */
static config cfg = {
    .help = 0,
    .debug = 0,
    .stats = 0,
    .stdin = 1,
    .reverse_sort = 0,
    .lisp_print = 0,
    .print_count = 0,
    .print_all = 0,
    .all_uniq = 0,
    .interactive = 0,
    .prompt = 1,
    .filestream = 0,
    .file = NULL,
    .query = NULL,
    .min_word_size = 3,
    .evc = 0,
    .extra_valid_chars = NULL,
    .eic = 0,
    .extra_invalid_chars = NULL,
    .search_method = starts,
    .max_token_size = 1000
};

static void print_help(char *argv0)
{
    fprintf(stderr,
	    "fcomp - parse text for string tokens and search for them\n");
    fprintf(stderr, "Copyright (C) 2019  Anastasis Grammenos\n");
    fprintf(stderr,
	    "This program is licenced under GPLv2. See source tree for details.\n\n");
    fprintf(stderr, "Usage:\n~~~~~~\n");
    fprintf(stderr, "%s [query] [-f FILE] [...]\n\n", argv0);
    fprintf(stderr, "%8s %4s  %15s %50s\n", "Options", "", "Mnemonic",
	    "Description");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "~~~~~~~", "", "~~~~~~~~",
	    "~~~~~~~~~~~");
    fprintf(stderr, "%8s %4s  %15s %50s\n\n", "-h", "", "help",
	    "Print this help message");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "query", "", "",
	    "The term to be matched agains the tokens");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-q", "[..]", "query",
	    "Same");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-f", "[..]", "file",
	    "Select the input file to use");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "stdin", "[..]", "",
	    "Input can come from rediretion as well as files");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-z", "", "fuzzy",
	    "Set the search method to fuzzy");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-x", "", "exact",
	    "Set the search method to exact match");
    fprintf(stderr, "%8s %4s  %15s %50s\n\n", "", "", "",
	    "(Default is starts_with)");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-r", "", "reverse",
	    "Reverse the sorting of matches");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-c", "", "count",
	    "Print the count of each matched token");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-l", "", "lisp",
	    "Print matched tokens in a lisp list");
    fprintf(stderr, "%8s %4s  %15s %50s\n\n", "-u", "", "unique",
	    "When -a is passed, don't print duplicates");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-a", "", "all",
	    "Print all tokens of input");
    fprintf(stderr, "%8s %4s  %15s %50s\n\n", "", "", "",
	    "(Performs no search)");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-v", "[..]", "valid chars",
	    "Set extra valid chars for tokens");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-i", "[..]", "invalid chars",
	    "Set extra invalid chars for tokens");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-w", "[..]", "word length",
	    "Set min word length to count as token");
    fprintf(stderr, "%8s %4s  %15s %50s\n\n", "-t", "[..]", "token length",
	    "Set max token length to parse");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-d", "", "debug",
	    "Show debug information");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-s", "", "stats",
	    "Print some stats");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "-I", "", "interactive",
	    "Run with interactive query input");
    fprintf(stderr, "%8s %4s  %15s %50s\n", "", "", "",
	    "(Pass it twice to disable prompt)");
}

static void print_cfg()
{
    fprintf(stderr, "\nValues:\n~~~~~~~\n");
    fprintf(stderr, "Input file: %68s\n", cfg.stdin ? "stdin" : cfg.file);
    fprintf(stderr, "Query: %73s\n", cfg.query ? cfg.query : "---");
    fprintf(stderr, "Search method: %65s\n",
	    cfg.search_method ==
	    starts ? "starts with" : (cfg.search_method ==
				      exact ? "exact match" : "fuzzy"));
    fprintf(stderr, "Minimun word size: %61d\n", cfg.min_word_size);
    fprintf(stderr, "Extra valid chars: %61s\n",
	    cfg.evc ? cfg.extra_valid_chars : "---");
    fprintf(stderr, "Extra invalid chars: %59s\n",
	    cfg.eic ? cfg.extra_invalid_chars : "---");
    fprintf(stderr, "Flags:\n");
    fprintf(stderr, "  [-d:%4s] ", cfg.debug ? "on" : "off");
    fprintf(stderr, "[-s:%4s] ", cfg.stats ? "on" : "off");
    fprintf(stderr, "[-f:%4s] ", cfg.stdin ? "off" : "on");
    fprintf(stderr, "[-r:%4s] ", cfg.reverse_sort ? "on" : "off");
    fprintf(stderr, "[-l:%4s]\n", cfg.lisp_print ? "on" : "off");
    fprintf(stderr, "  [-c:%4s] ", cfg.print_count ? "on" : "off");
    fprintf(stderr, "[-a:%4s] ", cfg.print_all ? "on" : "off");
    fprintf(stderr, "[-u:%4s] ", cfg.all_uniq ? "on" : "off");
    fprintf(stderr, "[-v:%4s] ", cfg.evc ? "on" : "off");
    fprintf(stderr, "[-i:%4s]\n", cfg.eic ? "on" : "off");
}

static void print_stats()
{
    fprintf(stderr, "\nStats:\n~~~~~~\n");
    fprintf(stderr, "Discarded chars:\t%d\n", st.discarded);
    if (st.tok_results) {
	fprintf(stderr, "%s", st.tok_results);
	free(st.tok_results);
    }
    if (st.search_results) {
	fprintf(stderr, "%s", st.search_results);
	free(st.search_results);
    }
    if (st.unique_results) {
	fprintf(stderr, "%s", st.unique_results);
	free(st.unique_results);
    }
}

static int parse_cli(int argc, char *argv[])
{
    if (argc < 2)
	return -1;
    char c;
    while ((c = getopt(argc, argv, "-hIxzsaudclrq:F:f:i:v:w:t:")) != -1) {
	switch (c) {
	case 'I':
	    if (cfg.interactive) {
		cfg.prompt = 0;
	    }
	    cfg.interactive = 1;
	    break;
	case 'F':
	    cfg.stdin = 0;
	    cfg.filestream = 1;
	    cfg.file = optarg;
	    break;
	case 'h':
	    cfg.help = 1;
	    break;
	case 'd':
	    cfg.debug = 1;
	    break;
	case 'u':
	    cfg.all_uniq = 1;
	    break;
	case 's':
	    cfg.stats = 1;
	    break;
	case 'a':
	    cfg.print_all = 1;
	    break;
	case 'x':
	    cfg.search_method = exact;
	    break;
	case 'z':
	    cfg.search_method = fuz;
	    break;
	case 'c':
	    cfg.print_count = 1;
	    break;
	case 'l':
	    cfg.lisp_print = 1;
	    break;
	case 'f':
	    cfg.stdin = 0;
	    cfg.file = optarg;
	    break;
	case 'v':
	    cfg.evc = 1;
	    cfg.extra_valid_chars = optarg;
	    break;
	case 'i':
	    cfg.eic = 1;
	    cfg.extra_invalid_chars = optarg;
	    break;
	case 'w':
	    cfg.min_word_size = atoi(optarg);
	    break;
	case 't':
	    cfg.max_token_size = atoi(optarg);
	    break;
	case 'r':
	    cfg.reverse_sort = 1;
	    break;
	case '\1':
        case 'q':
	    cfg.query = optarg;
	    break;
	case '?':
	    if (optopt == 'w') {
		fprintf(stderr, "Specify minimum word length after -%c\n",
			optopt);
	    } else if (optopt == 'v') {
		fprintf(stderr,
			"Specify extra valid chars after -%c\n", optopt);
	    } else if (optopt == 'i') {
		fprintf(stderr,
			"Specify extra invalid chars after -%c\n", optopt);
	    } else if (optopt == 'f') {
		fprintf(stderr,
			"Specify file to read after -%c\n", optopt);
	    } else if (optopt == 't') {
		fprintf(stderr,
			"Specify max token size after -%c\n", optopt);
	    }
	default:
	    return -1;
	}
    }
    return 0;
}

/**
 * Check if a character is valid according to the default
 * and extra valid characters */
static int is_valid(const char c)
{
    if (cfg.eic) {
	for (size_t i = 0; i < strlen(cfg.extra_invalid_chars); i++) {
	    if (cfg.extra_invalid_chars[i] == c)
		return 0;
	}
    }
    for (size_t i = 0; i < (sizeof(valid) / sizeof(valid[0])); i++) {
        if (valid[i] == c)
            return 1;
    }
    if (cfg.evc) {
        for (size_t i = 0; i < strlen(cfg.extra_valid_chars); i++) {
            if (cfg.extra_valid_chars[i] == c)
                return 1;
        }
    }
    return 0;
}

/**
 * Add by refference */
static void radd(slist * l, char *str)
{
    if (l->n == 0)
	l->s = (char **) malloc(sizeof(char *));
    else
	l->s = (char **) realloc(l->s, (l->n + 1) * sizeof(char *));

    l->s[l->n] = str;
    l->n++;
}

/**
 * Add by value */
static void sadd(slist * l, const char *tmp)
{
    if (l->n == 0)
	l->s = (char **) malloc(sizeof(char *));
    else
	l->s = (char **) realloc(l->s, (l->n + 1) * sizeof(char *));

    l->s[l->n] = strdup(tmp);
    l->n++;
}

/**
 * Add by refference to the result */
static void cadd(result * r, char *str)
{
    if (r->n == 0) {
	r->tok = (token **) malloc(sizeof(token *));
    } else {
	r->tok = (token **) realloc(r->tok, (r->n + 1) * sizeof(token *));
    }

    struct token *tok;
    tok = (token *) malloc(sizeof(token));
    if (!tok)
	fprintf(stderr, "Err\n");
    tok->s = str;
    tok->count = 1;

    r->tok[r->n] = tok;

    r->n++;
}

/**
 * free result */
static void cfree(result * res)
{
    for (unsigned int i = 0; i < res->n; i++) {
	free(res->tok[i]);
    }
    free(res->tok);
    res->n = 0;
}

/**
 * free slist */
static void sfree(slist * l)
{
    for (unsigned int i = 0; i < l->n; i++) {
	if (l->s[i])
	    free(l->s[i]);
    }
    if (l->s)
	free(l->s);
    l->n = 0;
}

/**
 * print slist */
static void pp(slist * l)
{
    for (unsigned int i = 0; i < l->n; i++) {
	printf("%s\n", l->s[i]);
    }
}

/**
 * Check if @str is the same as @c */
static int exact(const char *str, const char *c)
{
    if (strlen(str) != strlen(c))
	return 0;
    for (size_t i = 0; i < strlen(c); i++)
	if (str[i] != c[i])
	    return 0;
    return -1;
}

/**
 * Check if @str starts with @c */
static int starts(const char *str, const char *c)
{
    for (size_t i = 0; i < strlen(c); i++)
	if (str[i] != c[i])
	    return 0;
    return -1;
}

/**
 * Check if @str contains @c in the correct order
 * (e.g str=example, c=xl => e_x_amp_l_e) */
static int fuz(const char *str, const char *c)
{
    size_t i = 0;
    size_t j = 0;
    for (; i < strlen(str); i++) {
	if (str[i] == c[j]) {
	    j++;
	    if (j == strlen(c))
		return -1;
	}
    }
    return 0;
}

/**
 * Search an slist for @query and place the matches on @res
 * The search method is in the config struct */
static int search(const slist * l, const char *query, slist * res)
{
    int flag = 0;
    for (unsigned int i = 0; i < l->n; i++) {
	if ((*cfg.search_method) (l->s[i], query)) {
	    radd(res, l->s[i]);
	    flag = 1;
	}
    }
    return flag;
}

/**
 * Count the entries of a __sorted__ slist and fill
 * the @res result struct with unique entries along with the count */
static void count(slist * l, result * res)
{
    cadd(res, l->s[0]);
    for (unsigned int i = 1; i < l->n; i++) {
	if (strcmp(l->s[i], res->tok[res->n - 1]->s) == 0) {
	    res->tok[res->n - 1]->count++;
	} else
	    cadd(res, l->s[i]);
    }
}

static void finalize_str(char *str, unsigned int n, slist * l)
{
    if (n > cfg.min_word_size) {
	str[n] = '\0';
	sadd(l, str);
    }
}

static int cmpstringp(const void *p1, const void *p2)
{
    /* The actual arguments to this function are "pointers to
       pointers to char", but strcmp(3) arguments are "pointers
       to char", hence the following cast plus dereference */

    return strcmp(*(char *const *) p1, *(char *const *) p2);
}

static int cmpint(const void *p1, const void *p2)
{
    token *a = *(token * const *) p1;
    token *b = *(token * const *) p2;

    if (a->count < b->count)
	return 1;
    if (b->count > a->count)
	return -1;
    return 0;
}

static int cmpint_r(const void *p1, const void *p2)
{
    token *a = *(token * const *) p1;
    token *b = *(token * const *) p2;

    if (a->count > b->count)
	return 1;
    if (b->count < a->count)
	return -1;
    return 0;
}

static void pc(const result * res)
{
    if (cfg.lisp_print) {
	printf("( ");
	for (unsigned int i = 0; i < res->n - 1; i++) {
	    printf("\"%s\", ", res->tok[i]->s);
	}
	printf("\"%s\" )\n", res->tok[res->n - 1]->s);
    } else {
	for (unsigned int i = 0; i < res->n; i++) {
	    if (cfg.print_count)
		printf("[%d] ", res->tok[i]->count);
	    printf("%s\n", res->tok[i]->s);
	}
    }
}

/**
 * Fill an slist with tokens from @f */
static int tokenize(FILE * f, slist * l)
{
    unsigned int n = 0;
    int c;
    char *tmp = NULL;

    while ((c = fgetc(f)) != EOF) {
	if (!is_valid(c)) {
	    st.discarded++;
	    if (tmp) {
		finalize_str(tmp, n, l);
		free(tmp);
		tmp = NULL;
	    }
	    n = 0;
	    continue;
	}
	if (!tmp)
	    tmp = (char *) malloc(cfg.max_token_size);
	if (n < cfg.max_token_size)
	    tmp[n++] = (char) c;
	else {
	    fprintf(stderr,
		    "Max token size %d is not enough.\n",
		    cfg.max_token_size);
	    return -1;
	}
    }
    if (tmp) {
	finalize_str(tmp, n, l);
	free(tmp);
    }
    return 0;
}

static void sort_by_count(result * r)
{
    if (cfg.reverse_sort)
	qsort(&r->tok[0], r->n, sizeof(token *), cmpint_r);
    else
	qsort(&r->tok[0], r->n, sizeof(token *), cmpint);
}

static void get_slist_stats(slist * l)
{
    if (l->n > 0) {
	char tmp[] = "Total tokens:";
	st.tok_results = (char *)
	    malloc((strlen(tmp) + snprintf(NULL, 0, "%d", l->n) +
		    4) * sizeof(char));
	sprintf(st.tok_results, "%s\t\t%d\n", tmp, l->n);
    }
}

static void get_search_stats(slist * l)
{
    if (l->n > 0) {
	char tmp[] = "Total matches:";
	st.search_results = (char *)
	    malloc((strlen(tmp) + snprintf(NULL, 0, "%d", l->n) +
		    4) * sizeof(char));
	sprintf(st.search_results, "%s\t\t%d\n", tmp, l->n);
    }
}

static void get_result_stats(result * r)
{
    if (r->n > 0) {
	char tmp[] = "Unique tokens:";
	st.unique_results = (char *)
	    malloc((strlen(tmp) + snprintf(NULL, 0, "%d", r->n) +
		    4) * sizeof(char));
	sprintf(st.unique_results, "%s\t\t%d\n", tmp, r->n);
    }
}

void clean_stdin(void)
{
    int c;
    do {
	c = getchar();
    } while (c != '\n' && c != EOF);
}

static void prompt(slist * l)
{
    int r = 0;
    char p[20] = "";
    char *tmp = NULL;
    if (cfg.prompt)
	sprintf(p, "[%d]> ", r);
    fflush(NULL);
    while ((tmp = linenoise(p)) != NULL) {
	slist search_res = { 0 };
	if (search(l, tmp, &search_res)) {
	    result count_res = { 0 };
	    /* sort the results */
	    qsort(&search_res.s[0], search_res.n, sizeof(char *),
		  cmpstringp);

	    /* count the unique */
	    count(&search_res, &count_res);
	    sort_by_count(&count_res);

	    r = count_res.n;
	    /* print them */
	    pc(&count_res);

	    cfree(&count_res);
	}
	if (cfg.prompt)
	    sprintf(p, "[%d]> ", r);
	r = 0;
	free(search_res.s);
	free(tmp);
	tmp = NULL;
    }
    if (tmp)
	free(tmp);
}

static int set_input(FILE **f)
{
    if (cfg.stdin) {
	if (cfg.interactive) {
	    fprintf(stderr,
		    "Can't read from stdin in interactive mode.\n");
	    return -1;
	}
	*f = stdin;
    } else if (cfg.filestream) {
        if (!cfg.file || strcmp(cfg.file, "") == 0)
            return -1;
	*f = fmemopen(cfg.file, strlen(cfg.file), "r");
    } else {
	*f = fopen(cfg.file, "r");
	if (!f) {
	    fprintf(stderr, "Couldn't open %s\n", cfg.file);
	    return -1;
	}
    }
    return 0;
}

static void get_uniq(slist * l, result *r)
{
    /* sort the results */
    qsort(&l->s[0], l->n, sizeof(char *),
          cmpstringp);

    /* count the unique, put it in result */
    count(l, r);
    sort_by_count(r);

    if (cfg.stats)
        get_result_stats(r);
}

int main(int argc, char *argv[])
{
    int rc = 0;
    FILE *f = NULL;
    slist token_list = { 0 };
    slist ref_list = { 0 };
    slist *listp = NULL;
    result count_res = { 0 };

    if (parse_cli(argc, argv)
	|| cfg.help) {
	print_help(argv[0]);
	if (cfg.help)
	    return 0;
	return -1;
    }

    if (cfg.query == NULL && !cfg.print_all && !cfg.interactive) {
	fprintf(stderr, "Query missing ... terminating\n");
	return -1;
    }

    if ((rc = set_input(&f)))
        goto done;

    if ((rc = tokenize(f, &token_list)))
	goto done;

    if (cfg.stats)
	get_slist_stats(&token_list);

    if (cfg.interactive) {
	prompt(&token_list);
	goto done;
    }

    if (cfg.print_all) {
        if (cfg.all_uniq)
            listp = &token_list;
        else 
            pp(&token_list);
    } else {
	/* search for the query */
	if (search(&token_list, cfg.query, &ref_list)) {
            listp = &ref_list;
            if (cfg.stats)
		get_search_stats(&ref_list);
	}
    }

    if (listp) {
        if (listp->n != 0) {
            get_uniq(listp, &count_res);
            pc(&count_res);
            cfree(&count_res);
        }

        if (listp == &ref_list)
            free(ref_list.s);
    }


    if (cfg.debug)
	print_cfg();
    if (cfg.stats)
	print_stats();

  done:
    sfree(&token_list);
    if (f) fclose(f);
    return rc;
}