Try to simulate a human (to play abuser games on FICS)
[rattatechess.git] / utils.cpp
blob1471d5dcb054693e911de1af446cec980c1f1a25
1 /***************************************************************************
2 utils.cpp - sytem dependent utilities
3 -------------------
4 begin : lun ott 24 2005
5 copyright : (C) 2005-2007 by Maurizio Monge
6 email : monge@linuz.sns.it
7 ***************************************************************************/
9 /***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
18 #include "utils.h"
19 #include <stdlib.h>
20 #include <string.h>
22 char **get_tokenized(int* numtokens)
24 return fget_tokenized(stdin, numtokens);
27 char **get_tokenized(const char *whitespaces, int* numtokens)
29 return fget_tokenized(stdin, whitespaces, numtokens);
32 char **fget_tokenized(FILE* f, int* numtokens)
34 return fget_tokenized(f, " \v\t\r\n", numtokens);
37 char **fget_tokenized(FILE* f, const char *whitespaces, int* numtokens)
39 char str[4096];
40 if(!fgets(str, 4096, f))
41 return NULL;
42 return tokenize(str, whitespaces, numtokens);
45 char **tokenize(const char *str, int* numtokens)
47 return tokenize(str, " \v\t\r\n", numtokens);
50 char **tokenize(const char *str, const char *whitespaces, int* numtokens)
52 int len = strlen(str);
53 const char *ptr = str;
54 int ntoks = 0;
56 while(1)
58 ptr += strspn(ptr, whitespaces);
59 int s = strcspn(ptr, whitespaces);
61 if(!s)
62 break;
63 ptr += s;
64 ntoks++;
67 //printf("ntoks = %d\n", ntoks);
69 void* block = malloc((ntoks+1)*sizeof(char*) + len+1);
70 char** retv = (char**)block;
71 char* buf = (char*)block + (ntoks+1)*sizeof(char*);
73 ptr = str;
74 ntoks = 0;
76 while(1)
78 ptr += strspn(ptr, whitespaces);
79 //printf("-> \"%s\"\n", ptr);
80 if(!*ptr)
81 break;
82 retv[ntoks++] = buf;
84 bool quoted = false;
85 while( *ptr && (quoted || (strchr(whitespaces, *ptr) == NULL) ) )
87 if(*ptr == '"')
89 quoted = !quoted;
90 ptr++;
91 continue;
94 if(quoted && *ptr == '\\')
96 ptr++;
97 switch(*ptr)
99 case '"':
100 *buf++ = '"';
101 ptr++;
102 break;
103 case '\\':
104 *buf++ = '\\';
105 ptr++;
106 break;
107 case '\0':
108 *buf++ = '\\';
109 break;
110 default:
111 *buf++ = *ptr++;
112 break;
114 continue;
117 *buf++ = *ptr++;
119 *buf++ = '\0';
120 if(quoted)
121 printf("Error! Missing terminating '\"' while parsing!\n");
122 if(!*ptr)
123 break;
125 if(numtokens)
126 *numtokens = ntoks;
127 retv[ntoks++] = NULL;
128 return retv;