1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5int pos(char *haystack, char *needle)
6{
7	if (strstr(haystack, needle)) {
8		return (int) strstr(haystack, needle) - (int) haystack;
9	} else {
10		return -1;
11	}
12}
13
14void cutto(char *str, int len)
15{
16	memmove(str, str + len, strlen(str) - len + 1);
17}
18
19void mystrncpy(char *dest, char *src, int len)
20{
21	strncpy(dest, src, len);
22	*(dest + len) = 0;
23}
24
25int replace(char *str, char *what, char *by)
26{
27	char *foo, *bar = str;
28    int i = 0;
29	while ((foo = strstr(bar, what))) {
30        bar = foo + strlen(by);
31		memmove(bar,
32				foo + strlen(what), strlen(foo + strlen(what)) + 1);
33		memcpy(foo, by, strlen(by));
34        i++;
35	}
36    return i;
37}
38
39/* int_from_list(char *list, int n)
40 * returns the n'th integer element from a string like '2,5,12-15,20-23'
41 * if n is out of range or *list is out of range, -1 is returned.
42 */
43
44int int_from_list(char *list, int n)
45{
46    char *str, *tok;
47    int count = -1, firstrun = 1;
48
49    str = (char *) malloc(sizeof(char) * (strlen(list) + 2));
50    if (!str)
51        return -1;
52
53    memset(str, 0, strlen(list) + 2);
54    strncpy(str, list, strlen(list));
55
56    /* apppend ',' to the string so we can always use strtok() */
57	str[strlen(list)] = ',';
58
59    for (;;) {
60        if (firstrun)
61            tok = strtok(str, ",");
62        else
63            tok = strtok(NULL, ",");
64
65        if (!tok || *tok == '\0') {
66			free(str);
67            return -1;
68		}
69
70        if (strchr(tok, '-')) {
71            char *start, *end;
72            int s, e;
73            start = tok;
74            end = strchr(tok, '-');
75            *end = '\0';
76            end++;
77            if (!*start || !*end) {
78				free(str);
79                return -1;
80			}
81            s = atoi(start);
82            e = atoi(end);
83            if (s < 1 || e < 1 || e < s) {
84				free(str);
85                return -1;
86			}
87            count += e - s + 1;
88            if (count >= n) {
89				free(str);
90                return (e - (count - n));
91			}
92        } else {
93            count++;
94            if (count == n) {
95				int val = atoi(tok);
96				free(str);
97                return val;
98			}
99        }
100        firstrun = 0;
101    }
102}
103