forked from GPSBabel/gpsbabel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_util.cc
562 lines (491 loc) · 14.9 KB
/
csv_util.cc
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
/*
Utilities for parsing Character Separated Value files (CSV)
Copyright (C) 2002 Alex Mottram (geo_alexm at cox-internet.com)
Copyright (C) 2002-2014 Robert Lipe, [email protected]
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 <cassert> // for assert
#include <cmath> // for fabs
#include <cstdlib> // for strtod
#include <cstring> // for strlen, strchr, strncmp, strcmp, memmove, strcpy, strcspn, strncpy
#include <QByteArray> // for QByteArray
#include <QChar> // for QChar
#include <QDebug> // for QDebug
#include <QRegularExpression> // for QRegularExpression
#include <QString> // for QString, operator+
#include "defs.h"
#include "csv_util.h"
#include "src/core/logging.h" // for Warning
#define MYNAME "CSV_UTIL"
#define ISWHITESPACE(a) ((a == ' ') || (a == '\t'))
/*********************************************************************/
/* csv_stringclean() - remove any unwanted characters from string. */
/* returns copy of string. */
/* usage: p = csv_stringclean(stringtoclean, "&,\"") */
/* (strip out ampersands, commas, and quotes. */
/*********************************************************************/
QString
csv_stringclean(const QString& source, const QString& to_nuke)
{
QString r = source;
if (!to_nuke.isEmpty()) {
// avoid problematic regular rexpressions, e.g. xmapwpt generated [:\n:],
// or one can imagine [0-9] when we meant the characters, '0', '-', and '9',
// or one can imagine [^a] when we meant the characters '^' and 'a'.
QRegularExpression regex = QRegularExpression(QStringLiteral("[%1]").arg(QRegularExpression::escape(to_nuke)));
assert(regex.isValid());
r.remove(regex);
}
return r;
}
// csv_stringtrim() - trim whitespace and leading and trailing
// enclosures (quotes)
// returns a copy of the modified string
// usage: p = csv_stringtrim(string, "\"", 0)
QString
csv_stringtrim(const QString& string, const QString& enclosure, int strip_max)
{
if (string.isEmpty()) {
return string;
}
int elen = enclosure.size();
/* trim off leading and trailing whitespace */
QString retval = string.trimmed();
/* if no maximum strippage, assign a reasonable value to max */
if (strip_max == 0) {
strip_max = 9999;
}
/* if we have enclosures, skip past them in pairs */
if (elen > 0) {
int stripped = 0;
while (
(stripped < strip_max) &&
(retval.size() >= (elen * 2)) &&
(retval.startsWith(enclosure)) &&
(retval.endsWith(enclosure))) {
retval = retval.mid(elen, retval.size() - (elen * 2));
stripped++;
}
}
return retval;
}
// RFC4180 method, but we don't handle line breaks within a field.
// for enclosure = "
// make str = blank into nothing
// make str = foo into "foo"
// make str = foo"bar into "foo""bar"
// No, that doesn't seem obvious to me, either...
QString
csv_enquote(const QString& str, const QString& enclosure)
{
QString retval = str;
if (enclosure.size() > 0) {
retval = enclosure + retval.replace(enclosure, enclosure + enclosure) + enclosure;
}
return retval;
}
// RFC4180 method, but we don't handle line breaks within a field,
// and we strip spaces from the ends.
// csv_dequote() - trim whitespace, leading and trailing
// enclosures (quotes), and de-escape
// internal enclosures.
// usage: p = csv_dequote(string, "\"")
QString
csv_dequote(const QString& string, const QString& enclosure)
{
if (string.isEmpty()) {
return string;
}
int elen = enclosure.size();
/* trim off leading and trailing whitespace */
QString retval = string.trimmed();
if (elen > 0) {
/* If the string is enclosed in enclosures */
if (retval.startsWith(enclosure) && retval.endsWith(enclosure)) {
/* strip the enclosures */
retval = retval.mid(elen, retval.size() - (elen * 2));
/* replace any contained escaped enclosures */
retval = retval.replace(enclosure + enclosure, enclosure);
}
}
return retval;
}
/*****************************************************************************/
/* csv_linesplit() - extract data fields from a delimited string. designed */
/* to handle quoted and delimited data within quotes. */
/* usage: p = csv_lineparse(string, ",", "\"", line) */
/*****************************************************************************/
QStringList
csv_linesplit(const QString& string, const QString& delimited_by,
const QString& enclosed_in, const int line_no, CsvQuoteMethod method)
{
QStringList retval;
const bool hyper_whitespace_delimiter = delimited_by == "\\w";
/*
* This is tacky. Our "csv" format is actually "commaspace" format.
* Changing that causes unwanted churn, but it also makes "real"
* comma separated data (such as likely to be produced by Excel, etc.)
* unreadable. So we silently change it here on a read and let the
* whitespace eater consume the space.
*/
QString delimiter = delimited_by;
if (delimited_by == ", ") {
delimiter = ",";
}
/* length of delimiters and enclosures */
int dlen = 0;
if ((!delimiter.isEmpty()) && (!hyper_whitespace_delimiter)) {
dlen = delimiter.size();
}
int elen = enclosed_in.size();
int p = 0;
bool endofline = false;
while (!endofline) {
bool efound = false;
bool dfound = false;
bool enclosed = false;
/* the beginning of the string we start with (this pass) */
const int sp = p;
while (p < string.size() && !dfound) {
if ((elen > 0) && string.mid(p).startsWith(enclosed_in)) {
efound = true;
p += elen;
enclosed = !enclosed;
continue;
}
if (!enclosed) {
if ((dlen > 0) && string.mid(p).startsWith(delimiter)) {
dfound = true;
} else if (hyper_whitespace_delimiter && string.at(p).isSpace()) {
dfound = true;
while ((p < string.size()) && string.at(p).isSpace()) {
p++;
}
} else {
p++;
}
} else {
p++;
}
}
QString value = string.mid(sp, p - sp);
if (efound) {
if (method == CsvQuoteMethod::rfc4180) {
value = csv_dequote(value, enclosed_in);
} else {
value = csv_stringtrim(value, enclosed_in, 0);
}
}
if (dfound) {
/* skip over the delimiter */
p += dlen;
} else {
endofline = true;
}
if (enclosed) {
Warning() << MYNAME":" <<
"Warning- Unbalanced Field Enclosures" <<
enclosed_in <<
"on line" <<
line_no;
}
retval.append(value);
}
return retval;
}
/*****************************************************************************/
/* dec_to_intdeg() - convert decimal degrees to integer degreees */
/* usage: i = dec_to_intdeg(31.1234); */
/*****************************************************************************/
int
dec_to_intdeg(const double d)
{
int ideg = 0;
if (d >= 0) {
ideg = (2147483647) - (d * 8388608);
} else {
ideg = (2147483647) - (fabs(d) * 8388608) + 1;
}
return(ideg);
}
/*****************************************************************************/
/* intdeg_to_dec() - convert integer degrees to decimal degreees */
/* usage: lat = dec_to_intdeg(ilat); */
/*****************************************************************************/
double
intdeg_to_dec(const int ideg)
{
double d;
if (ideg >= 0) {
d = ((2147483647) - ideg) / 8388608.0;
} else {
d = ((-2147483647-1) + ideg) / 8388608.0;
}
return(d);
}
/*****************************************************************************/
/* decdir_to_dec() - convert a decimal/direction value into pure decimal. */
/* usage: lat = decdir_to_dec("W90.1234"); */
/* lat = decdir_to_dec("30.1234N"); */
/*****************************************************************************/
double
decdir_to_dec(const char* decdir)
{
char* p;
int sign = 0;
const char* cp = &decdir[0];
if ((*cp == 'W') || (*cp == 'S')) {
sign = -1;
} else if ((*cp == 'N') || (*cp == 'E')) {
sign = 1;
}
double rval = sign ? strtod(&decdir[1], &p) : strtod(&decdir[0], &p);
if (sign == 0) {
if ((*p == 'W') || (*p == 'S')) {
sign = -1;
} else if ((*p == 'N') || (*p == 'E')) {
sign = 1;
}
}
return(rval * sign);
}
/*****************************************************************************/
/* ddmmdir_to_degrees() - convert ddmm/direction value into degrees */
/* usage: lat = ddmmdir_to_degrees("W90.1234"); */
/* lat = ddmmdir_to_degrees("30.1234N"); */
/*****************************************************************************/
double
ddmmdir_to_degrees(const char* ddmmdir)
{
// if not N or E, prepend a '-' to ddmm2degrees input
// see XT_LAT_NMEA which handles ddmm directly
if (strchr(ddmmdir, 'W') || strchr(ddmmdir, 'S')) {
return ddmm2degrees(- strtod(ddmmdir, nullptr));
}
return ddmm2degrees(strtod(ddmmdir, nullptr));
}
/*****************************************************************************
* human_to_dec() - convert a "human-readable" lat and/or lon to decimal
* usage: human_to_dec( "N 41° 09.12′ W 085° 09.36′", &lat, &lon );
* human_to_dec( "41 9 5.652 N", &lat, &lon );
*
* which: 0-no preference 1-prefer lat 2-prefer lon
*****************************************************************************/
void
human_to_dec(const QString& instr, double* outlat, double* outlon, int which)
{
double unk[3] = {999,999,999};
double lat[3] = {999,999,999};
double lon[3] = {999,999,999};
int latsign = 0;
int lonsign = 0;
int unksign = 1;
double* numres = unk;
int numind = 0;
// Allow comma as decimal separator.
const QByteArray inbytes = instr.toUtf8().replace(',', '.');
const char* cur = inbytes.constData();
while (cur && *cur) {
switch (*cur) {
case 'n':
case 's':
case 'N':
case 'S':
if (unk[0] != 999) {
numind = 0;
numres = unk;
lat[0] = unk[0];
lat[1] = unk[1];
lat[2] = unk[2];
unk[0] = unk[1] = unk[2] = 999;
} else {
numres = lat;
numind = 0;
lat[0] = lat[1] = lat[2] = 999;
}
if (*cur == 'n' || *cur == 'N') {
latsign = 1;
} else {
latsign = -1;
}
cur++;
break;
case 'w':
case 'e':
case 'W':
case 'E':
if (unk[0] != 999) {
numind = 0;
numres = unk;
lon[0] = unk[0];
lon[1] = unk[1];
lon[2] = unk[2];
unk[0] = unk[1] = unk[2] = 999;
} else {
numres = lon;
numind = 0;
lon[0] = lon[1] = lon[2] = 999;
}
if (*cur == 'e' || *cur == 'E') {
lonsign = 1;
} else {
lonsign = -1;
}
cur++;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '.':
char* end;
numres[numind] = strtod(cur, &end);
cur = end;
break;
case '-':
unksign = -1;
cur++;
break;
default:
if (numres[numind] != 999) {
numind++;
if (numind > 2) {
numres = unk;
numind = 0;
}
}
cur++;
break;
}
}
if (lat[0] == 999 && lon[0] == 999) {
if (which == 1) {
lat[0] = unk[0];
lat[1] = unk[1];
lat[2] = unk[2];
latsign = unksign;
} else if (which == 2) {
lon[0] = unk[0];
lon[1] = unk[1];
lon[2] = unk[2];
lonsign = unksign;
}
}
if (outlat) {
if (lat[0] != 999) {
*outlat = lat[0];
}
if (lat[1] != 999) {
*outlat += lat[1]/60.0;
}
if (lat[2] != 999) {
*outlat += lat[2]/3600.0;
}
if (*outlat > 360) {
*outlat = ddmm2degrees(*outlat); /* NMEA style */
}
if (latsign) {
*outlat *= latsign;
}
}
if (outlon) {
if (lon[0] != 999) {
*outlon = lon[0];
}
if (lon[1] != 999) {
*outlon += lon[1]/60.0;
}
if (lon[2] != 999) {
*outlon += lon[2]/3600.0;
}
if (*outlon > 360) {
*outlon = ddmm2degrees(*outlon); /* NMEA style */
}
if (lonsign) {
*outlon *= lonsign;
}
}
}
/*
* dec_to_human - convert decimal degrees to human readable
*/
QString
dec_to_human(const char* format, const char* dirs, double val)
{
int index = 0;
int intvals[3] = {0,0,0};
double dblvals[3] = {0,0,0};
int sign = (val < 0) ? 0 : 1;
dblvals[0] = fabs(val);
intvals[0] = (int)dblvals[0];
dblvals[1] = 60*(dblvals[0]-intvals[0]);
intvals[1] = (int)dblvals[1];
dblvals[2] = 60*(dblvals[1]-intvals[1]);
intvals[2] = (int)dblvals[2];
char* subformat = (char*) xmalloc(strlen(format)+2);
const char* formatptr = format;
QString buff;
while (formatptr && *formatptr) {
strcpy(subformat, formatptr);
char* percent = strchr(subformat, '%');
if (percent) {
char* type = percent+1+strcspn(percent+1, "cdiouxXeEfgG%");
*(type+1) = '\0';
switch (*type) {
case 'c':
buff += QString::asprintf(subformat, dirs[sign]);
break;
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'X':
if (index>2) {
fatal(MYNAME ": too many format specifiers\n");
}
buff += QString::asprintf(subformat, intvals[index]);
index++;
break;
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
if (index>2) {
fatal(MYNAME ": too many format specifiers\n");
}
buff += QString::asprintf(subformat, dblvals[index]);
index++;
break;
case '%':
buff += subformat;
break;
default:
fatal(MYNAME ": invalid format specifier\n");
break;
}
} else {
buff += subformat;
}
formatptr += strlen(subformat);
}
xfree(subformat);
return buff;
}