updated on Thu Jan 12 04:00:44 UTC 2012
[aur-mirror.git] / pdfselect / pdfselect_i.c
blobab4e576cbaa8fccce6cc5f6fa85137a1388abb78
1 #include <stddef.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
6 void add_pages(char* buffer, int sr, int er, int npages) {
7 int i;
8 for (i = sr; i <= er && i < npages && i > 0; ++i) {
9 buffer[i] = 0;
13 void add_page(char* buffer, int sr, int npages) {
14 if (sr > 0 && sr < npages) {
15 buffer[sr] = 0;
19 void apply_range(char* buffer, int npages, const char* range) {
20 if (range != NULL) {
21 int sr;
22 int er;
23 const char* t;
24 enum {
25 brange = 1,
26 erange = 2,
27 end = 4,
28 none = 8
29 } state;
30 state = brange;
31 memset(buffer, 1, npages); /* no pages. */
32 t = range;
33 while ((state & end) == 0) {
34 switch (*range) {
35 case '0': case '1': case '2': case '3': case '4':
36 case '5': case '6': case '7': case '8': case '9':
37 ++range; /* case [:digit:] */
38 break;
39 case '-':
40 ++range;
41 if ((state & brange) != 0) {
42 sscanf(t, "%d-", &sr);
43 state &= ~brange;
44 state |= erange;
46 t = range;
47 break;
48 case '\0':
49 state |= end;
50 --range; /* no break */
51 case ',':
52 ++range;
53 if ((state & brange) != 0) {
54 sscanf(t, "%d,", &sr);
55 add_page(buffer, sr, npages);
56 } else if ((state & erange) != 0) {
57 state &= ~erange;
58 state |= brange;
59 sscanf(t, "%d-", &er);
60 add_pages(buffer, sr, er, npages);
62 t = range;
63 break;
64 default:
65 t = range;
66 ++range;
72 int main(int argc, char** argv) {
73 int i;
74 int npages;
75 char r = 0;
76 char e = 0;
77 char o = 0;
78 char* range = NULL;
80 if (argc == 1) {
81 fprintf(stderr, "%s nofpages [e | o] [r] [range]\n", argv[0]);
82 return -1;
85 sscanf(argv[1], "%d", &npages);
86 if (npages <= 0) {
87 fprintf(stderr, "Number of pages invalid.\n");
88 return -1;
91 for (i = 2; i < argc; ++i) {
92 if (strcmp(argv[i], "r") == 0) {
93 r = 1;
94 } else if (strcmp(argv[i], "e") == 0) {
95 e = 1;
96 } else if (strcmp(argv[i], "o") == 0) {
97 o = 1;
98 } else {
99 range = argv[i];
102 if (e == 1 && o == 1) {
103 e = 0;
104 o = 0;
107 ++npages;
109 /* if buffer[i] is zero, i is in the range. */
110 char* buffer = calloc(1, npages);
111 if (buffer == NULL) {
112 fprintf(stderr, "Sorry, internal error.\n");
113 return -1;
115 apply_range(buffer, npages, range);
116 if (e == 1) {
117 for (i = 1; i < npages; i += 2) {
118 buffer[i] = 1;
121 if (o == 1) {
122 for (i = 2; i < npages; i += 2) {
123 buffer[i] = 1;
126 buffer[0] = 1; /* page zero does not exist. */
127 if (r == 0) {
128 for (i = 0; i < npages; ++i) {
129 if (buffer[i] == 0) printf("%d ", i);
131 }else {
132 for (i=npages; i > 0; ) {
133 --i;
134 if (buffer[i] == 0) printf("%d ", i);
137 free(buffer);
139 return 0;