cavern: Improve caret info for bad *cs custom
[survex.git] / src / commands.c
blob653a54cf5449a05a278c92b08f1ee955822c3d00
1 /* commands.c
2 * Code for directives
3 * Copyright (C) 1991-2003,2004,2005,2006,2010,2011,2012,2013,2014,2015,2016,2019 Olly Betts
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <assert.h>
25 #include <limits.h>
26 #include <stddef.h> /* for offsetof */
27 #include <string.h>
29 #include <proj.h>
30 #if PROJ_VERSION_MAJOR < 8 || \
31 (PROJ_VERSION_MAJOR == 8 && PROJ_VERSION_MINOR < 2)
32 /* Needed for proj_factors workaround */
33 # include <proj_experimental.h>
34 #endif
36 #include "cavern.h"
37 #include "commands.h"
38 #include "datain.h"
39 #include "date.h"
40 #include "debug.h"
41 #include "filename.h"
42 #include "message.h"
43 #include "netbits.h"
44 #include "netskel.h"
45 #include "out.h"
46 #include "readval.h"
47 #include "str.h"
49 #define WGS84_DATUM_STRING "EPSG:4326"
51 static void
52 default_grade(settings *s)
54 /* Values correspond to those in bcra5.svx */
55 s->Var[Q_POS] = (real)sqrd(0.05);
56 s->Var[Q_LENGTH] = (real)sqrd(0.05);
57 s->Var[Q_BACKLENGTH] = (real)sqrd(0.05);
58 s->Var[Q_COUNT] = (real)sqrd(0.05);
59 s->Var[Q_DX] = s->Var[Q_DY] = s->Var[Q_DZ] = (real)sqrd(0.05);
60 s->Var[Q_BEARING] = (real)sqrd(rad(0.5));
61 s->Var[Q_GRADIENT] = (real)sqrd(rad(0.5));
62 s->Var[Q_BACKBEARING] = (real)sqrd(rad(0.5));
63 s->Var[Q_BACKGRADIENT] = (real)sqrd(rad(0.5));
64 /* SD of plumbed legs (0.25 degrees?) */
65 s->Var[Q_PLUMB] = (real)sqrd(rad(0.25));
66 /* SD of level legs (0.25 degrees?) */
67 s->Var[Q_LEVEL] = (real)sqrd(rad(0.25));
68 s->Var[Q_DEPTH] = (real)sqrd(0.05);
71 static void
72 default_truncate(settings *s)
74 s->Truncate = INT_MAX;
77 static void
78 default_case(settings *s)
80 s->Case = LOWER;
83 static reading default_order[] = { Fr, To, Tape, Comp, Clino, End };
85 static void
86 default_style(settings *s)
88 s->style = STYLE_NORMAL;
89 s->ordering = default_order;
90 s->dash_for_anon_wall_station = fFalse;
93 static void
94 default_prefix(settings *s)
96 s->Prefix = root;
99 static void
100 default_translate(settings *s)
102 int i;
103 short *t;
104 if (s->next && s->next->Translate == s->Translate) {
105 t = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
106 memcpy(t - 1, s->Translate - 1, sizeof(short) * 257);
107 s->Translate = t;
109 /* SVX_ASSERT(EOF==-1);*/ /* important, since we rely on this */
110 t = s->Translate;
111 memset(t - 1, 0, sizeof(short) * 257);
112 for (i = '0'; i <= '9'; i++) t[i] = SPECIAL_NAMES;
113 for (i = 'A'; i <= 'Z'; i++) t[i] = SPECIAL_NAMES;
114 for (i = 'a'; i <= 'z'; i++) t[i] = SPECIAL_NAMES;
116 t['\t'] |= SPECIAL_BLANK;
117 t[' '] |= SPECIAL_BLANK;
118 t[','] |= SPECIAL_BLANK;
119 t[';'] |= SPECIAL_COMMENT;
120 t['\032'] |= SPECIAL_EOL; /* Ctrl-Z, so olde DOS text files are handled ok */
121 t[EOF] |= SPECIAL_EOL;
122 t['\n'] |= SPECIAL_EOL;
123 t['\r'] |= SPECIAL_EOL;
124 t['*'] |= SPECIAL_KEYWORD;
125 t['-'] |= SPECIAL_OMIT;
126 t['\\'] |= SPECIAL_ROOT;
127 t['.'] |= SPECIAL_SEPARATOR;
128 t['_'] |= SPECIAL_NAMES;
129 t['-'] |= SPECIAL_NAMES; /* Added in 0.97 prerelease 4 */
130 t['.'] |= SPECIAL_DECIMAL;
131 t['-'] |= SPECIAL_MINUS;
132 t['+'] |= SPECIAL_PLUS;
133 #if 0 /* FIXME */
134 t['{'] |= SPECIAL_OPEN;
135 t['}'] |= SPECIAL_CLOSE;
136 #endif
139 void
140 default_units(settings *s)
142 int quantity;
143 for (quantity = 0; quantity < Q_MAC; quantity++) {
144 if (TSTBIT(ANG_QMASK, quantity))
145 s->units[quantity] = (real)(M_PI / 180.0); /* degrees */
146 else
147 s->units[quantity] = (real)1.0; /* metres */
149 s->f_clino_percent = s->f_backclino_percent = fFalse;
150 s->f_bearing_quadrants = s->f_backbearing_quadrants = fFalse;
153 void
154 default_calib(settings *s)
156 int quantity;
157 for (quantity = 0; quantity < Q_MAC; quantity++) {
158 s->z[quantity] = (real)0.0;
159 s->sc[quantity] = (real)1.0;
163 static void
164 default_flags(settings *s)
166 s->flags = 0;
169 extern void
170 default_all(settings *s)
172 default_truncate(s);
173 s->infer = 0;
174 default_case(s);
175 default_style(s);
176 default_prefix(s);
177 default_translate(s);
178 default_grade(s);
179 default_units(s);
180 default_calib(s);
181 default_flags(s);
184 char *buffer = NULL;
185 static int buf_len;
187 static char *ucbuffer = NULL;
189 /* read token */
190 extern void
191 get_token(void)
193 skipblanks();
194 get_token_no_blanks();
197 extern void
198 get_token_no_blanks(void)
200 int i = -1;
202 s_zero(&buffer);
203 osfree(ucbuffer);
204 while (isalpha(ch)) {
205 s_catchar(&buffer, &buf_len, (char)ch);
206 nextch();
209 if (!buffer) s_catchar(&buffer, &buf_len, '\0');
211 ucbuffer = osmalloc(buf_len);
212 do {
213 i++;
214 ucbuffer[i] = toupper(buffer[i]);
215 } while (buffer[i]);
216 #if 0
217 printf("get_token_no_blanks() got “%s”\n", buffer);
218 #endif
221 /* read word */
222 static void
223 get_word(void)
225 s_zero(&buffer);
226 skipblanks();
227 while (!isBlank(ch) && !isEol(ch)) {
228 s_catchar(&buffer, &buf_len, (char)ch);
229 nextch();
232 if (!buffer) s_catchar(&buffer, &buf_len, '\0');
233 #if 0
234 printf("get_word() got “%s”\n", buffer);
235 #endif
238 /* match_tok() now uses binary chop
239 * tab argument should be alphabetically sorted (ascending)
241 extern int
242 match_tok(const sztok *tab, int tab_size)
244 int a = 0, b = tab_size - 1, c;
245 int r;
246 assert(tab_size > 0); /* catch empty table */
247 /* printf("[%d,%d]",a,b); */
248 while (a <= b) {
249 c = (unsigned)(a + b) / 2;
250 /* printf(" %d",c); */
251 r = strcmp(tab[c].sz, ucbuffer);
252 if (r == 0) return tab[c].tok; /* match */
253 if (r < 0)
254 a = c + 1;
255 else
256 b = c - 1;
258 return tab[tab_size].tok; /* no match */
261 typedef enum {
262 CMD_NULL = -1, CMD_ALIAS, CMD_BEGIN, CMD_CALIBRATE, CMD_CASE, CMD_COPYRIGHT,
263 CMD_CS, CMD_DATA, CMD_DATE, CMD_DECLINATION, CMD_DEFAULT, CMD_END,
264 CMD_ENTRANCE, CMD_EQUATE, CMD_EXPORT, CMD_FIX, CMD_FLAGS, CMD_INCLUDE,
265 CMD_INFER, CMD_INSTRUMENT, CMD_PREFIX, CMD_REF, CMD_REQUIRE, CMD_SD,
266 CMD_SET, CMD_SOLVE, CMD_TEAM, CMD_TITLE, CMD_TRUNCATE, CMD_UNITS
267 } cmds;
269 static const sztok cmd_tab[] = {
270 {"ALIAS", CMD_ALIAS},
271 {"BEGIN", CMD_BEGIN},
272 {"CALIBRATE", CMD_CALIBRATE},
273 {"CASE", CMD_CASE},
274 {"COPYRIGHT", CMD_COPYRIGHT},
275 {"CS", CMD_CS},
276 {"DATA", CMD_DATA},
277 {"DATE", CMD_DATE},
278 {"DECLINATION", CMD_DECLINATION},
279 #ifndef NO_DEPRECATED
280 {"DEFAULT", CMD_DEFAULT},
281 #endif
282 {"END", CMD_END},
283 {"ENTRANCE", CMD_ENTRANCE},
284 {"EQUATE", CMD_EQUATE},
285 {"EXPORT", CMD_EXPORT},
286 {"FIX", CMD_FIX},
287 {"FLAGS", CMD_FLAGS},
288 {"INCLUDE", CMD_INCLUDE},
289 {"INFER", CMD_INFER},
290 {"INSTRUMENT",CMD_INSTRUMENT},
291 #ifndef NO_DEPRECATED
292 {"PREFIX", CMD_PREFIX},
293 #endif
294 {"REF", CMD_REF},
295 {"REQUIRE", CMD_REQUIRE},
296 {"SD", CMD_SD},
297 {"SET", CMD_SET},
298 {"SOLVE", CMD_SOLVE},
299 {"TEAM", CMD_TEAM},
300 {"TITLE", CMD_TITLE},
301 {"TRUNCATE", CMD_TRUNCATE},
302 {"UNITS", CMD_UNITS},
303 {NULL, CMD_NULL}
306 /* masks for units which are length and angles respectively */
307 #define LEN_UMASK (BIT(UNITS_METRES) | BIT(UNITS_FEET) | BIT(UNITS_YARDS))
308 #define ANG_UMASK (BIT(UNITS_DEGS) | BIT(UNITS_GRADS) | BIT(UNITS_MINUTES))
310 /* ordering must be the same as the units enum */
311 const real factor_tab[] = {
312 1.0, METRES_PER_FOOT, (METRES_PER_FOOT*3.0),
313 (M_PI/180.0), (M_PI/180.0), (M_PI/200.0), 0.01, (M_PI/180.0/60.0)
316 const int units_to_msgno[] = {
317 /*m*/424,
318 /*ft*/428,
319 -1, /* yards */
320 /*°*/344, /* quadrants */
321 /*°*/344,
322 /*ᵍ*/345,
323 /*%*/96,
324 -1 /* minutes */
327 int get_length_units(int quantity) {
328 double factor = pcs->units[quantity];
329 if (fabs(factor - METRES_PER_FOOT) <= REAL_EPSILON ||
330 fabs(factor - METRES_PER_FOOT * 3.0) <= REAL_EPSILON) {
331 return UNITS_FEET;
333 return UNITS_METRES;
336 int get_angle_units(int quantity) {
337 double factor = pcs->units[quantity];
338 if (fabs(factor - M_PI / 200.0) <= REAL_EPSILON) {
339 return UNITS_GRADS;
341 return UNITS_DEGS;
344 static int
345 get_units(unsigned long qmask, bool percent_ok)
347 static const sztok utab[] = {
348 {"DEGREES", UNITS_DEGS },
349 {"DEGS", UNITS_DEGS },
350 {"FEET", UNITS_FEET },
351 {"GRADS", UNITS_GRADS },
352 {"METERS", UNITS_METRES },
353 {"METRES", UNITS_METRES },
354 {"METRIC", UNITS_METRES },
355 {"MILS", UNITS_DEPRECATED_ALIAS_FOR_GRADS },
356 {"MINUTES", UNITS_MINUTES },
357 {"PERCENT", UNITS_PERCENT },
358 {"PERCENTAGE", UNITS_PERCENT },
359 {"QUADRANTS", UNITS_QUADRANTS },
360 {"QUADS", UNITS_QUADRANTS },
361 {"YARDS", UNITS_YARDS },
362 {NULL, UNITS_NULL }
364 int units;
365 get_token();
366 units = match_tok(utab, TABSIZE(utab));
367 if (units == UNITS_NULL) {
368 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown units “%s”*/35, buffer);
369 return UNITS_NULL;
371 /* Survex has long misdefined "mils" as an alias for "grads", of which
372 * there are 400 in a circle. There are several definitions of "mils"
373 * with a circle containing 2000π SI milliradians, 6400 NATO mils, 6000
374 * Warsaw Pact mils, and 6300 Swedish streck, and they aren't in common
375 * use by cave surveyors, so we now just warn if mils are used.
377 if (units == UNITS_DEPRECATED_ALIAS_FOR_GRADS) {
378 compile_diagnostic(DIAG_WARN|DIAG_BUF|DIAG_SKIP,
379 /*Units “%s” are deprecated, assuming “grads” - see manual for details*/479,
380 buffer);
381 units = UNITS_GRADS;
383 if (units == UNITS_PERCENT && percent_ok &&
384 !(qmask & ~(BIT(Q_GRADIENT)|BIT(Q_BACKGRADIENT)))) {
385 return units;
387 if (units == UNITS_QUADRANTS &&
388 !(qmask & ~(BIT(Q_BEARING)|BIT(Q_BACKBEARING)))) {
389 return units;
391 if (((qmask & LEN_QMASK) && !TSTBIT(LEN_UMASK, units)) ||
392 ((qmask & ANG_QMASK) && !TSTBIT(ANG_UMASK, units))) {
393 /* TRANSLATORS: Note: In English you talk about the *units* of a single
394 * measurement, but the correct term in other languages may be singular.
396 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Invalid units “%s” for quantity*/37, buffer);
397 return UNITS_NULL;
399 return units;
402 /* returns mask with bit x set to indicate quantity x specified */
403 static unsigned long
404 get_qlist(unsigned long mask_bad)
406 static const sztok qtab[] = {
407 {"ALTITUDE", Q_DZ },
408 {"BACKBEARING", Q_BACKBEARING },
409 {"BACKCLINO", Q_BACKGRADIENT }, /* alternative name */
410 {"BACKCOMPASS", Q_BACKBEARING }, /* alternative name */
411 {"BACKGRADIENT", Q_BACKGRADIENT },
412 {"BACKLENGTH", Q_BACKLENGTH },
413 {"BACKTAPE", Q_BACKLENGTH }, /* alternative name */
414 {"BEARING", Q_BEARING },
415 {"CEILING", Q_UP }, /* alternative name */
416 {"CLINO", Q_GRADIENT }, /* alternative name */
417 {"COMPASS", Q_BEARING }, /* alternative name */
418 {"COUNT", Q_COUNT },
419 {"COUNTER", Q_COUNT }, /* alternative name */
420 {"DECLINATION", Q_DECLINATION },
421 {"DEFAULT", Q_DEFAULT }, /* not a real quantity... */
422 {"DEPTH", Q_DEPTH },
423 {"DOWN", Q_DOWN },
424 {"DX", Q_DX }, /* alternative name */
425 {"DY", Q_DY }, /* alternative name */
426 {"DZ", Q_DZ }, /* alternative name */
427 {"EASTING", Q_DX },
428 {"FLOOR", Q_DOWN }, /* alternative name */
429 {"GRADIENT", Q_GRADIENT },
430 {"LEFT", Q_LEFT },
431 {"LENGTH", Q_LENGTH },
432 {"LEVEL", Q_LEVEL},
433 {"NORTHING", Q_DY },
434 {"PLUMB", Q_PLUMB},
435 {"POSITION", Q_POS },
436 {"RIGHT", Q_RIGHT },
437 {"TAPE", Q_LENGTH }, /* alternative name */
438 {"UP", Q_UP },
439 {NULL, Q_NULL }
441 unsigned long qmask = 0;
442 int tok;
443 filepos fp;
445 while (1) {
446 get_pos(&fp);
447 get_token();
448 tok = match_tok(qtab, TABSIZE(qtab));
449 if (tok == Q_DEFAULT && !(mask_bad & BIT(Q_DEFAULT))) {
450 /* Only recognise DEFAULT if it is the first quantity, and then don't
451 * look for any more. */
452 if (qmask == 0)
453 return BIT(Q_DEFAULT);
454 break;
456 /* bail out if we reach the table end with no match */
457 if (tok == Q_NULL) break;
458 qmask |= BIT(tok);
459 if (qmask & mask_bad) {
460 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown instrument “%s”*/39, buffer);
461 return 0;
465 if (qmask == 0) {
466 /* TRANSLATORS: A "quantity" is something measured like "LENGTH",
467 * "BEARING", "ALTITUDE", etc. */
468 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown quantity “%s”*/34, buffer);
469 } else {
470 set_pos(&fp);
473 return qmask;
476 #define SPECIAL_UNKNOWN 0
477 static void
478 cmd_set(void)
480 static const sztok chartab[] = {
481 {"BLANK", SPECIAL_BLANK },
482 /*FIXME {"CLOSE", SPECIAL_CLOSE }, */
483 {"COMMENT", SPECIAL_COMMENT },
484 {"DECIMAL", SPECIAL_DECIMAL },
485 {"EOL", SPECIAL_EOL }, /* EOL won't work well */
486 {"KEYWORD", SPECIAL_KEYWORD },
487 {"MINUS", SPECIAL_MINUS },
488 {"NAMES", SPECIAL_NAMES },
489 {"OMIT", SPECIAL_OMIT },
490 /*FIXME {"OPEN", SPECIAL_OPEN }, */
491 {"PLUS", SPECIAL_PLUS },
492 #ifndef NO_DEPRECATED
493 {"ROOT", SPECIAL_ROOT },
494 #endif
495 {"SEPARATOR", SPECIAL_SEPARATOR },
496 {NULL, SPECIAL_UNKNOWN }
498 int mask;
499 int i;
501 get_token();
502 mask = match_tok(chartab, TABSIZE(chartab));
504 if (mask == SPECIAL_UNKNOWN) {
505 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown character class “%s”*/42, buffer);
506 return;
509 #ifndef NO_DEPRECATED
510 if (mask == SPECIAL_ROOT) {
511 if (root_depr_count < 5) {
512 /* TRANSLATORS: Use of the ROOT character (which is "\" by default) is
513 * deprecated, so this error would be generated by:
515 * *equate \foo.7 1
517 * If you're unsure what "deprecated" means, see:
518 * https://en.wikipedia.org/wiki/Deprecation */
519 compile_diagnostic(DIAG_WARN|DIAG_BUF, /*ROOT is deprecated*/25);
520 if (++root_depr_count == 5)
521 /* TRANSLATORS: If you're unsure what "deprecated" means, see:
522 * https://en.wikipedia.org/wiki/Deprecation */
523 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
526 #endif
528 /* if we're currently using an inherited translation table, allocate a new
529 * table, and copy old one into it */
530 if (pcs->next && pcs->next->Translate == pcs->Translate) {
531 short *p;
532 p = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
533 memcpy(p - 1, pcs->Translate - 1, sizeof(short) * 257);
534 pcs->Translate = p;
537 skipblanks();
539 /* clear this flag for all non-alphanums */
540 for (i = 0; i < 256; i++)
541 if (!isalnum(i)) pcs->Translate[i] &= ~mask;
543 /* now set this flag for all specified chars */
544 while (!isEol(ch)) {
545 if (!isalnum(ch)) {
546 pcs->Translate[ch] |= mask;
547 } else if (tolower(ch) == 'x') {
548 int hex;
549 filepos fp;
550 get_pos(&fp);
551 nextch();
552 if (!isxdigit(ch)) {
553 set_pos(&fp);
554 break;
556 hex = isdigit(ch) ? ch - '0' : tolower(ch) - 'a';
557 nextch();
558 if (!isxdigit(ch)) {
559 set_pos(&fp);
560 break;
562 hex = hex << 4 | (isdigit(ch) ? ch - '0' : tolower(ch) - 'a');
563 pcs->Translate[hex] |= mask;
564 } else {
565 break;
567 nextch();
571 static void
572 check_reentry(prefix *survey, const filepos* fpos_ptr)
574 /* Don't try to check "*prefix \" or "*begin \" */
575 if (!survey->up) return;
576 if (TSTBIT(survey->sflags, SFLAGS_PREFIX_ENTERED)) {
577 static int reenter_depr_count = 0;
578 filepos fp_tmp;
580 if (reenter_depr_count >= 5)
581 return;
583 get_pos(&fp_tmp);
584 set_pos(fpos_ptr);
585 /* TRANSLATORS: The first of two warnings given when a survey which has
586 * already been completed is reentered. This example file crawl.svx:
588 * *begin crawl ; <- second warning here
589 * 1 2 9.45 234 -01
590 * *end crawl
591 * *begin crawl ; <- first warning here
592 * 2 3 7.67 223 -03
593 * *end crawl
595 * Would lead to:
597 * crawl.svx:4: Reentering an existing survey is deprecated
598 * crawl.svx:1: Originally entered here
600 * If you're unsure what "deprecated" means, see:
601 * https://en.wikipedia.org/wiki/Deprecation */
602 compile_diagnostic(DIAG_WARN|DIAG_TOKEN, /*Reentering an existing survey is deprecated*/29);
603 set_pos(&fp_tmp);
604 /* TRANSLATORS: The second of two warnings given when a survey which has
605 * already been completed is reentered. This example file crawl.svx:
607 * *begin crawl
608 * 1 2 9.45 234 -01 # <- second warning here
609 * *end crawl
610 * *begin crawl # <- first warning here
611 * 2 3 7.67 223 -03
612 * *end crawl
614 * Would lead to:
616 * crawl.svx:3: Reentering an existing survey is deprecated
617 * crawl.svx:1: Originally entered here
619 * If you're unsure what "deprecated" means, see:
620 * https://en.wikipedia.org/wiki/Deprecation */
621 compile_diagnostic_pfx(DIAG_WARN, survey, /*Originally entered here*/30);
622 if (++reenter_depr_count == 5) {
623 /* After we've warned about 5 uses of the same deprecated feature, we
624 * give up for the rest of the current processing run.
626 * If you're unsure what "deprecated" means, see:
627 * https://en.wikipedia.org/wiki/Deprecation */
628 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
630 } else {
631 survey->sflags |= BIT(SFLAGS_PREFIX_ENTERED);
632 survey->filename = file.filename;
633 survey->line = file.line;
637 #ifndef NO_DEPRECATED
638 static void
639 cmd_prefix(void)
641 static int prefix_depr_count = 0;
642 prefix *survey;
643 filepos fp;
644 /* Issue warning first, so "*prefix \" warns first that *prefix is
645 * deprecated and then that ROOT is...
647 if (prefix_depr_count < 5) {
648 /* TRANSLATORS: If you're unsure what "deprecated" means, see:
649 * https://en.wikipedia.org/wiki/Deprecation */
650 compile_diagnostic(DIAG_WARN|DIAG_BUF, /**prefix is deprecated - use *begin and *end instead*/6);
651 if (++prefix_depr_count == 5)
652 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
654 get_pos(&fp);
655 survey = read_prefix(PFX_SURVEY|PFX_ALLOW_ROOT);
656 pcs->Prefix = survey;
657 check_reentry(survey, &fp);
659 #endif
661 static void
662 cmd_alias(void)
664 /* Currently only two forms are supported:
665 * *alias station - ..
666 * *alias station -
668 get_token();
669 if (strcmp(ucbuffer, "STATION") != 0)
670 goto bad;
671 get_word();
672 if (strcmp(buffer, "-") != 0)
673 goto bad;
674 get_word();
675 if (*buffer && strcmp(buffer, "..") != 0)
676 goto bad;
677 pcs->dash_for_anon_wall_station = (*buffer != '\0');
678 return;
679 bad:
680 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Bad *alias command*/397);
683 static void
684 cmd_begin(void)
686 settings *pcsNew;
688 pcsNew = osnew(settings);
689 *pcsNew = *pcs; /* copy contents */
690 pcsNew->begin_lineno = file.line;
691 pcsNew->next = pcs;
692 pcs = pcsNew;
694 skipblanks();
695 pcs->begin_survey = NULL;
696 if (!isEol(ch) && !isComm(ch)) {
697 filepos fp;
698 prefix *survey;
699 get_pos(&fp);
700 survey = read_prefix(PFX_SURVEY|PFX_ALLOW_ROOT|PFX_WARN_SEPARATOR);
701 pcs->begin_survey = survey;
702 pcs->Prefix = survey;
703 check_reentry(survey, &fp);
704 f_export_ok = fTrue;
708 static void
709 invalidate_pj_cached(void)
711 /* Invalidate the cached PJ. */
712 if (pj_cached) {
713 proj_destroy(pj_cached);
714 pj_cached = NULL;
718 void pop_settings()
720 settings * p = pcs;
721 pcs = pcs->next;
722 SVX_ASSERT(pcs);
724 if (p->proj_str != pcs->proj_str) {
725 if (!p->proj_str || !pcs->proj_str ||
726 strcmp(p->proj_str, pcs->proj_str) != 0) {
727 invalidate_pj_cached();
729 /* free proj_str if not used by parent */
730 osfree(p->proj_str);
733 /* don't free default ordering or ordering used by parent */
734 if (p->ordering != default_order && p->ordering != pcs->ordering)
735 osfree((reading*)p->ordering);
737 /* free Translate if not used by parent */
738 if (!pcs || p->Translate != pcs->Translate)
739 osfree(p->Translate - 1);
741 /* free meta if not used by parent, or in this block */
742 if (p->meta && p->meta != pcs->meta && p->meta->ref_count == 0)
743 osfree(p->meta);
745 osfree(p);
748 static void
749 cmd_end(void)
751 prefix *survey, *begin_survey;
752 filepos fp;
754 if (pcs->begin_lineno == 0) {
755 if (pcs->next == NULL) {
756 /* more ENDs than BEGINs */
757 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*No matching BEGIN*/192);
758 } else {
759 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*END with no matching BEGIN in this file*/22);
761 return;
764 begin_survey = pcs->begin_survey;
766 pop_settings();
768 /* note need to read using root *before* BEGIN */
769 skipblanks();
770 if (isEol(ch) || isComm(ch)) {
771 survey = NULL;
772 } else {
773 get_pos(&fp);
774 survey = read_prefix(PFX_SURVEY|PFX_ALLOW_ROOT);
777 if (survey != begin_survey) {
778 if (survey) {
779 set_pos(&fp);
780 if (!begin_survey) {
781 /* TRANSLATORS: Used when a BEGIN command has no survey, but the
782 * END command does, e.g.:
784 * *begin
785 * 1 2 10.00 178 -01
786 * *end entrance <--[Message given here] */
787 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Matching BEGIN command has no survey name*/36);
788 } else {
789 /* TRANSLATORS: *BEGIN <survey> and *END <survey> should have the
790 * same <survey> if it’s given at all */
791 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Survey name doesn’t match BEGIN*/193);
793 skipline();
794 } else {
795 /* TRANSLATORS: Used when a BEGIN command has a survey name, but the
796 * END command omits it, e.g.:
798 * *begin entrance
799 * 1 2 10.00 178 -01
800 * *end <--[Message given here] */
801 compile_diagnostic(DIAG_WARN|DIAG_COL, /*Survey name omitted from END*/194);
806 static void
807 cmd_entrance(void)
809 prefix *pfx = read_prefix(PFX_STATION);
810 pfx->sflags |= BIT(SFLAGS_ENTRANCE);
813 static const prefix * first_fix_name = NULL;
814 static const char * first_fix_filename;
815 static unsigned first_fix_line;
817 static void
818 cmd_fix(void)
820 prefix *fix_name;
821 node *stn = NULL;
822 static prefix *name_omit_already = NULL;
823 static const char * name_omit_already_filename = NULL;
824 static unsigned int name_omit_already_line;
825 real x, y, z;
826 filepos fp;
828 fix_name = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
829 fix_name->sflags |= BIT(SFLAGS_FIXED);
831 get_pos(&fp);
832 get_token();
833 if (strcmp(ucbuffer, "REFERENCE") == 0) {
834 /* suppress "unused fixed point" warnings for this station */
835 fix_name->sflags |= BIT(SFLAGS_USED);
836 } else {
837 if (*ucbuffer) set_pos(&fp);
840 x = read_numeric(fTrue);
841 if (x == HUGE_REAL) {
842 /* If the end of the line isn't blank, read a number after all to
843 * get a more helpful error message */
844 if (!isEol(ch) && !isComm(ch)) x = read_numeric(fFalse);
846 if (x == HUGE_REAL) {
847 if (pcs->proj_str || proj_str_out) {
848 compile_diagnostic(DIAG_ERR|DIAG_COL|DIAG_SKIP, /*Coordinates can't be omitted when coordinate system has been specified*/439);
849 return;
852 if (fix_name == name_omit_already) {
853 compile_diagnostic(DIAG_WARN|DIAG_COL, /*Same station fixed twice with no coordinates*/61);
854 return;
857 /* TRANSLATORS: " *fix a " gives this message: */
858 compile_diagnostic(DIAG_WARN|DIAG_COL, /*FIX command with no coordinates - fixing at (0,0,0)*/54);
860 if (name_omit_already) {
861 /* TRANSLATORS: Emitted after second and subsequent "FIX command with
862 * no coordinates - fixing at (0,0,0)" warnings.
864 compile_diagnostic_at(DIAG_ERR|DIAG_COL,
865 name_omit_already_filename,
866 name_omit_already_line,
867 /*Already had FIX command with no coordinates for station “%s”*/441,
868 sprint_prefix(name_omit_already));
869 } else {
870 name_omit_already = fix_name;
871 name_omit_already_filename = file.filename;
872 name_omit_already_line = file.line;
875 x = y = z = (real)0.0;
876 } else {
877 real sdx;
878 y = read_numeric(fFalse);
879 z = read_numeric(fFalse);
881 if (pcs->proj_str && proj_str_out) {
882 PJ *transform = pj_cached;
883 if (!transform) {
884 transform = proj_create_crs_to_crs(PJ_DEFAULT_CTX,
885 pcs->proj_str,
886 proj_str_out,
887 NULL);
888 if (transform) {
889 /* Normalise the output order so x is longitude and y latitude - by
890 * default new PROJ has them switched for EPSG:4326 which just seems
891 * confusing.
893 PJ* pj_norm = proj_normalize_for_visualization(PJ_DEFAULT_CTX,
894 transform);
895 proj_destroy(transform);
896 transform = pj_norm;
899 pj_cached = transform;
902 if (proj_angular_input(transform, PJ_FWD)) {
903 /* Input coordinate system expects radians. */
904 x = rad(x);
905 y = rad(y);
908 PJ_COORD coord = {{x, y, z, HUGE_VAL}};
909 coord = proj_trans(transform, PJ_FWD, coord);
910 x = coord.xyzt.x;
911 y = coord.xyzt.y;
912 z = coord.xyzt.z;
914 if (x == HUGE_VAL || y == HUGE_VAL || z == HUGE_VAL) {
915 compile_diagnostic(DIAG_ERR, /*Failed to convert coordinates: %s*/436,
916 proj_errno_string(proj_errno(transform)));
917 /* Set dummy values which are finite. */
918 x = y = z = 0;
920 } else if (pcs->proj_str) {
921 compile_diagnostic(DIAG_ERR, /*The input projection is set but the output projection isn't*/437);
922 } else if (proj_str_out) {
923 compile_diagnostic(DIAG_ERR, /*The output projection is set but the input projection isn't*/438);
926 get_pos(&fp);
927 sdx = read_numeric(fTrue);
928 if (sdx <= 0) {
929 set_pos(&fp);
930 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_NUM, /*Standard deviation must be positive*/48);
931 return;
933 if (sdx != HUGE_REAL) {
934 real sdy, sdz;
935 real cxy = 0, cyz = 0, czx = 0;
936 get_pos(&fp);
937 sdy = read_numeric(fTrue);
938 if (sdy == HUGE_REAL) {
939 /* only one variance given */
940 sdy = sdz = sdx;
941 } else {
942 if (sdy <= 0) {
943 set_pos(&fp);
944 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_NUM, /*Standard deviation must be positive*/48);
945 return;
947 get_pos(&fp);
948 sdz = read_numeric(fTrue);
949 if (sdz == HUGE_REAL) {
950 /* two variances given - horizontal & vertical */
951 sdz = sdy;
952 sdy = sdx;
953 } else {
954 if (sdz <= 0) {
955 set_pos(&fp);
956 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_NUM, /*Standard deviation must be positive*/48);
957 return;
959 cxy = read_numeric(fTrue);
960 if (cxy != HUGE_REAL) {
961 /* covariances given */
962 cyz = read_numeric(fFalse);
963 czx = read_numeric(fFalse);
964 } else {
965 cxy = 0;
969 stn = StnFromPfx(fix_name);
970 if (!fixed(stn)) {
971 node *fixpt = osnew(node);
972 prefix *name;
973 name = osnew(prefix);
974 name->pos = osnew(pos);
975 name->ident = NULL;
976 name->shape = 0;
977 fixpt->name = name;
978 name->stn = fixpt;
979 name->up = NULL;
980 if (TSTBIT(pcs->infer, INFER_EXPORTS)) {
981 name->min_export = USHRT_MAX;
982 } else {
983 name->min_export = 0;
985 name->max_export = 0;
986 name->sflags = 0;
987 add_stn_to_list(&stnlist, fixpt);
988 POS(fixpt, 0) = x;
989 POS(fixpt, 1) = y;
990 POS(fixpt, 2) = z;
991 fix(fixpt);
992 fixpt->leg[0] = fixpt->leg[1] = fixpt->leg[2] = NULL;
993 addfakeleg(fixpt, stn, 0, 0, 0,
994 sdx * sdx, sdy * sdy, sdz * sdz
995 #ifndef NO_COVARIANCES
996 , cxy, cyz, czx
997 #endif
1001 if (!first_fix_name) {
1002 /* We track if we've fixed a station yet, and if so what the name
1003 * of the first fix was, so that we can issue an error if the
1004 * output coordinate system is set after fixing a station. */
1005 first_fix_name = fix_name;
1006 first_fix_filename = file.filename;
1007 first_fix_line = file.line;
1010 return;
1014 if (!first_fix_name) {
1015 /* We track if we've fixed a station yet, and if so what the name of the
1016 * first fix was, so that we can issue an error if the output coordinate
1017 * system is set after fixing a station. */
1018 first_fix_name = fix_name;
1019 first_fix_filename = file.filename;
1020 first_fix_line = file.line;
1023 stn = StnFromPfx(fix_name);
1024 if (!fixed(stn)) {
1025 POS(stn, 0) = x;
1026 POS(stn, 1) = y;
1027 POS(stn, 2) = z;
1028 fix(stn);
1029 return;
1032 if (x != POS(stn, 0) || y != POS(stn, 1) || z != POS(stn, 2)) {
1033 compile_diagnostic(DIAG_ERR, /*Station already fixed or equated to a fixed point*/46);
1034 return;
1036 /* TRANSLATORS: *fix a 1 2 3 / *fix a 1 2 3 */
1037 compile_diagnostic(DIAG_WARN, /*Station already fixed at the same coordinates*/55);
1040 static void
1041 cmd_flags(void)
1043 static const sztok flagtab[] = {
1044 {"DUPLICATE", FLAGS_DUPLICATE },
1045 {"NOT", FLAGS_NOT },
1046 {"SPLAY", FLAGS_SPLAY },
1047 {"SURFACE", FLAGS_SURFACE },
1048 {NULL, FLAGS_UNKNOWN }
1050 bool fNot = fFalse;
1051 bool fEmpty = fTrue;
1052 while (1) {
1053 int flag;
1054 get_token();
1055 /* If buffer is empty, it could mean end of line, or maybe
1056 * some non-letter junk which is better reported later */
1057 if (!buffer[0]) break;
1059 fEmpty = fFalse;
1060 flag = match_tok(flagtab, TABSIZE(flagtab));
1061 /* treat the second NOT in "NOT NOT" as an unknown flag */
1062 if (flag == FLAGS_UNKNOWN || (fNot && flag == FLAGS_NOT)) {
1063 compile_diagnostic(DIAG_ERR|DIAG_BUF, /*FLAG “%s” unknown*/68, buffer);
1064 /* Recover from “*FLAGS NOT BOGUS SURFACE” by ignoring "NOT BOGUS" */
1065 fNot = fFalse;
1066 } else if (flag == FLAGS_NOT) {
1067 fNot = fTrue;
1068 } else if (fNot) {
1069 pcs->flags &= ~BIT(flag);
1070 fNot = fFalse;
1071 } else {
1072 pcs->flags |= BIT(flag);
1076 if (fNot) {
1077 compile_diagnostic(DIAG_ERR|DIAG_BUF, /*Expecting “DUPLICATE”, “SPLAY”, or “SURFACE”*/188);
1078 } else if (fEmpty) {
1079 compile_diagnostic(DIAG_ERR|DIAG_BUF, /*Expecting “NOT”, “DUPLICATE”, “SPLAY”, or “SURFACE”*/189);
1083 static void
1084 cmd_equate(void)
1086 prefix *name1, *name2;
1087 bool fOnlyOneStn = fTrue; /* to trap eg *equate entrance.6 */
1088 filepos fp;
1090 get_pos(&fp);
1091 name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO);
1092 while (fTrue) {
1093 name2 = name1;
1094 skipblanks();
1095 if (isEol(ch) || isComm(ch)) {
1096 if (fOnlyOneStn) {
1097 set_pos(&fp);
1098 /* TRANSLATORS: EQUATE is a command name, so shouldn’t be
1099 * translated.
1101 * Here "station" is a survey station, not a train station.
1103 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_TOKEN, /*Only one station in EQUATE command*/33);
1105 return;
1108 name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO);
1109 process_equate(name1, name2);
1110 fOnlyOneStn = fFalse;
1114 static void
1115 report_missing_export(prefix *pfx, int depth)
1117 char *s;
1118 const char *p;
1119 prefix *survey = pfx;
1120 int i;
1121 for (i = depth + 1; i; i--) {
1122 survey = survey->up;
1123 SVX_ASSERT(survey);
1125 s = osstrdup(sprint_prefix(survey));
1126 p = sprint_prefix(pfx);
1127 if (survey->filename) {
1128 /* TRANSLATORS: A station must be exported out of each level it is in, so
1129 * this would give "Station “\outer.inner.1” not exported from survey
1130 * “\outer”)":
1132 * *equate entrance outer.inner.1
1133 * *begin outer
1134 * *begin inner
1135 * *export 1
1136 * 1 2 1.23 045 -6
1137 * *end inner
1138 * *end outer
1140 * Here "survey" is a "cave map" rather than list of questions - it should be
1141 * translated to the terminology that cavers using the language would use.
1143 compile_diagnostic_pfx(DIAG_ERR, survey,
1144 /*Station “%s” not exported from survey “%s”*/26, p, s);
1145 } else {
1146 compile_diagnostic(DIAG_ERR, /*Station “%s” not exported from survey “%s”*/26, p, s);
1148 osfree(s);
1151 static void
1152 cmd_export(void)
1154 prefix *pfx;
1156 fExportUsed = fTrue;
1157 do {
1158 int depth = 0;
1159 pfx = read_prefix(PFX_STATION|PFX_NEW);
1160 if (pfx == NULL) {
1161 /* The argument was an existing station. */
1162 /* FIXME */
1163 } else {
1164 prefix *p = pfx;
1165 while (p != NULL && p != pcs->Prefix) {
1166 depth++;
1167 p = p->up;
1169 /* Something like: *export \foo, but we've excluded use of root */
1170 SVX_ASSERT(p);
1172 /* *export \ or similar bogus stuff */
1173 SVX_ASSERT(depth);
1174 #if 0
1175 printf("C min %d max %d depth %d pfx %s\n",
1176 pfx->min_export, pfx->max_export, depth, sprint_prefix(pfx));
1177 #endif
1178 if (pfx->min_export == 0) {
1179 /* not encountered *export for this name before */
1180 if (pfx->max_export > depth) report_missing_export(pfx, depth);
1181 pfx->min_export = pfx->max_export = depth;
1182 } else if (pfx->min_export != USHRT_MAX) {
1183 /* FIXME: what to do if a station is marked for inferred exports
1184 * but is then explicitly exported? Currently we just ignore the
1185 * explicit export... */
1186 if (pfx->min_export - 1 > depth) {
1187 report_missing_export(pfx, depth);
1188 } else if (pfx->min_export - 1 < depth) {
1189 /* TRANSLATORS: Here "station" is a survey station, not a train station.
1191 * Exporting a station twice gives this error:
1193 * *begin example
1194 * *export 1
1195 * *export 1
1196 * 1 2 1.24 045 -6
1197 * *end example */
1198 compile_diagnostic(DIAG_ERR, /*Station “%s” already exported*/66,
1199 sprint_prefix(pfx));
1201 pfx->min_export = depth;
1203 skipblanks();
1204 } while (!isEol(ch) && !isComm(ch));
1207 static void
1208 cmd_data(void)
1210 static const sztok dtab[] = {
1211 {"ALTITUDE", Dz },
1212 {"BACKBEARING", BackComp },
1213 {"BACKCLINO", BackClino }, /* alternative name */
1214 {"BACKCOMPASS", BackComp }, /* alternative name */
1215 {"BACKGRADIENT", BackClino },
1216 {"BACKLENGTH", BackTape },
1217 {"BACKTAPE", BackTape }, /* alternative name */
1218 {"BEARING", Comp },
1219 {"CEILING", Up }, /* alternative name */
1220 {"CLINO", Clino }, /* alternative name */
1221 {"COMPASS", Comp }, /* alternative name */
1222 {"COUNT", Count }, /* FrCount&ToCount in multiline */
1223 {"DEPTH", Depth }, /* FrDepth&ToDepth in multiline */
1224 {"DEPTHCHANGE", DepthChange },
1225 {"DIRECTION", Dir },
1226 {"DOWN", Down },
1227 {"DX", Dx },
1228 {"DY", Dy },
1229 {"DZ", Dz },
1230 {"EASTING", Dx },
1231 {"FLOOR", Down }, /* alternative name */
1232 {"FROM", Fr },
1233 {"FROMCOUNT", FrCount },
1234 {"FROMDEPTH", FrDepth },
1235 {"GRADIENT", Clino },
1236 {"IGNORE", Ignore },
1237 {"IGNOREALL", IgnoreAll },
1238 {"LEFT", Left },
1239 {"LENGTH", Tape },
1240 {"NEWLINE", Newline },
1241 {"NORTHING", Dy },
1242 {"RIGHT", Right },
1243 {"STATION", Station }, /* Fr&To in multiline */
1244 {"TAPE", Tape }, /* alternative name */
1245 {"TO", To },
1246 {"TOCOUNT", ToCount },
1247 {"TODEPTH", ToDepth },
1248 {"UP", Up },
1249 {NULL, End }
1252 #define MASK_stns BIT(Fr) | BIT(To) | BIT(Station)
1253 #define MASK_tape BIT(Tape) | BIT(BackTape) | BIT(FrCount) | BIT(ToCount) | BIT(Count)
1254 #define MASK_dpth BIT(FrDepth) | BIT(ToDepth) | BIT(Depth) | BIT(DepthChange)
1255 #define MASK_comp BIT(Comp) | BIT(BackComp)
1256 #define MASK_clin BIT(Clino) | BIT(BackClino)
1258 #define MASK_NORMAL MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_clin
1259 #define MASK_DIVING MASK_NORMAL | MASK_dpth
1260 #define MASK_CARTESIAN MASK_stns | BIT(Dx) | BIT(Dy) | BIT(Dz)
1261 #define MASK_CYLPOLAR MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_dpth
1262 #define MASK_NOSURVEY MASK_stns
1263 #define MASK_PASSAGE BIT(Station) | BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down)
1265 /* readings which may be given for each style */
1266 static const unsigned long mask[] = {
1267 MASK_NORMAL, MASK_DIVING, MASK_CARTESIAN, MASK_CYLPOLAR, MASK_NOSURVEY,
1268 MASK_PASSAGE
1271 /* readings which may be omitted for each style */
1272 static const unsigned long mask_optional[] = {
1273 BIT(Dir) | BIT(Clino) | BIT(BackClino),
1274 BIT(Dir) | BIT(Clino) | BIT(BackClino),
1276 BIT(Dir),
1278 0 /* BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down), */
1281 /* all valid readings */
1282 static const unsigned long mask_all[] = {
1283 MASK_NORMAL | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1284 MASK_DIVING | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1285 MASK_CARTESIAN | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1286 MASK_CYLPOLAR | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1287 MASK_NOSURVEY | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1288 MASK_PASSAGE | BIT(Ignore) | BIT(IgnoreAll) | BIT(End)
1290 #define STYLE_DEFAULT -2
1291 #define STYLE_UNKNOWN -1
1293 static const sztok styletab[] = {
1294 {"CARTESIAN", STYLE_CARTESIAN },
1295 {"CYLPOLAR", STYLE_CYLPOLAR },
1296 {"DEFAULT", STYLE_DEFAULT },
1297 {"DIVING", STYLE_DIVING },
1298 {"NORMAL", STYLE_NORMAL },
1299 {"NOSURVEY", STYLE_NOSURVEY },
1300 {"PASSAGE", STYLE_PASSAGE },
1301 {"TOPOFIL", STYLE_NORMAL },
1302 {NULL, STYLE_UNKNOWN }
1305 #define m_multi (BIT(Station) | BIT(Count) | BIT(Depth))
1307 int style, k = 0;
1308 reading d;
1309 unsigned long mUsed = 0;
1310 int old_style = pcs->style;
1312 /* after a bad *data command ignore survey data until the next
1313 * *data command to avoid an avalanche of errors */
1314 pcs->style = STYLE_IGNORE;
1316 get_token();
1317 style = match_tok(styletab, TABSIZE(styletab));
1319 if (style == STYLE_DEFAULT) {
1320 default_style(pcs);
1321 return;
1324 if (style == STYLE_UNKNOWN) {
1325 if (!buffer[0]) {
1326 /* "*data" reinitialises the current style - for *data passage that
1327 * breaks the passage.
1329 pcs->style = style = old_style;
1330 goto reinit_style;
1332 /* TRANSLATORS: e.g. trying to refer to an invalid FNORD data style */
1333 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Data style “%s” unknown*/65, buffer);
1334 return;
1337 skipblanks();
1338 #ifndef NO_DEPRECATED
1339 /* Olde syntax had optional field for survey grade, so allow an omit
1340 * but issue a warning about it */
1341 if (isOmit(ch)) {
1342 static int data_depr_count = 0;
1343 if (data_depr_count < 5) {
1344 compile_diagnostic(DIAG_WARN|DIAG_BUF, /*“*data %s %c …” is deprecated - use “*data %s …” instead*/104,
1345 buffer, ch, buffer);
1346 if (++data_depr_count == 5)
1347 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
1349 nextch();
1351 #endif
1353 int kMac = 6; /* minimum for NORMAL style */
1354 reading *new_order = osmalloc(kMac * sizeof(reading));
1355 char *style_name = osstrdup(buffer);
1356 do {
1357 filepos fp;
1358 get_pos(&fp);
1359 get_token();
1360 d = match_tok(dtab, TABSIZE(dtab));
1361 /* only token allowed after IGNOREALL is NEWLINE */
1362 if (k && new_order[k - 1] == IgnoreAll && d != Newline) {
1363 set_pos(&fp);
1364 break;
1366 /* Note: an unknown token is reported as trailing garbage */
1367 if (!TSTBIT(mask_all[style], d)) {
1368 /* TRANSLATORS: a data "style" is something like NORMAL, DIVING, etc.
1369 * a "reading" is one of FROM, TO, TAPE, COMPASS, CLINO for NORMAL
1370 * style. Neither "style" nor "reading" is a keyword in the program.
1372 * This error complains about a "DEPTH" gauge reading in "NORMAL"
1373 * style, for example.
1375 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP,
1376 /*Reading “%s” not allowed in data style “%s”*/63,
1377 buffer, style_name);
1378 osfree(style_name);
1379 osfree(new_order);
1380 return;
1382 if (TSTBIT(mUsed, Newline) && TSTBIT(m_multi, d)) {
1383 /* TRANSLATORS: caused by e.g.
1385 * *data diving station newline depth tape compass
1387 * ("depth" needs to occur before "newline"). */
1388 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP,
1389 /*Reading “%s” must occur before NEWLINE*/225, buffer);
1390 osfree(style_name);
1391 osfree(new_order);
1392 return;
1394 /* Check for duplicates unless it's a special reading:
1395 * IGNOREALL,IGNORE (duplicates allowed) ; END (not possible)
1397 if (!((BIT(Ignore) | BIT(End) | BIT(IgnoreAll)) & BIT(d))) {
1398 if (TSTBIT(mUsed, d)) {
1399 /* TRANSLATORS: complains about a situation like trying to define
1400 * two from stations per leg */
1401 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Duplicate reading “%s”*/67, buffer);
1402 osfree(style_name);
1403 osfree(new_order);
1404 return;
1405 } else {
1406 /* Check for previously listed readings which are incompatible
1407 * with this one - e.g. Count vs FrCount */
1408 bool fBad = fFalse;
1409 switch (d) {
1410 case Station:
1411 if (mUsed & (BIT(Fr) | BIT(To))) fBad = fTrue;
1412 break;
1413 case Fr: case To:
1414 if (TSTBIT(mUsed, Station)) fBad = fTrue;
1415 break;
1416 case Count:
1417 if (mUsed & (BIT(FrCount) | BIT(ToCount) | BIT(Tape)))
1418 fBad = fTrue;
1419 break;
1420 case FrCount: case ToCount:
1421 if (mUsed & (BIT(Count) | BIT(Tape)))
1422 fBad = fTrue;
1423 break;
1424 case Depth:
1425 if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(DepthChange)))
1426 fBad = fTrue;
1427 break;
1428 case FrDepth: case ToDepth:
1429 if (mUsed & (BIT(Depth) | BIT(DepthChange))) fBad = fTrue;
1430 break;
1431 case DepthChange:
1432 if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(Depth)))
1433 fBad = fTrue;
1434 break;
1435 case Newline:
1436 if (mUsed & ~m_multi) {
1437 /* TRANSLATORS: e.g.
1439 * *data normal from to tape newline compass clino */
1440 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*NEWLINE can only be preceded by STATION, DEPTH, and COUNT*/226);
1441 osfree(style_name);
1442 osfree(new_order);
1443 return;
1445 if (k == 0) {
1446 /* TRANSLATORS: error from:
1448 * *data normal newline from to tape compass clino */
1449 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*NEWLINE can’t be the first reading*/222);
1450 osfree(style_name);
1451 osfree(new_order);
1452 return;
1454 break;
1455 default: /* avoid compiler warnings about unhandled enums */
1456 break;
1458 if (fBad) {
1459 /* Not entirely happy with phrasing this... */
1460 /* TRANSLATORS: This is an error from the *DATA command. It
1461 * means that a reading (which will appear where %s is isn't
1462 * valid as the list of readings has already included the same
1463 * reading, or an equivalent one (e.g. you can't have both
1464 * DEPTH and DEPTHCHANGE together). */
1465 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Reading “%s” duplicates previous reading(s)*/77,
1466 buffer);
1467 osfree(style_name);
1468 osfree(new_order);
1469 return;
1471 mUsed |= BIT(d); /* used to catch duplicates */
1474 if (k && new_order[k - 1] == IgnoreAll) {
1475 SVX_ASSERT(d == Newline);
1476 k--;
1477 d = IgnoreAllAndNewLine;
1479 if (k >= kMac) {
1480 kMac = kMac * 2;
1481 new_order = osrealloc(new_order, kMac * sizeof(reading));
1483 new_order[k++] = d;
1484 } while (d != End);
1486 if (k >= 2 && new_order[k - 2] == Newline) {
1487 /* TRANSLATORS: error from:
1489 * *data normal from to tape compass clino newline */
1490 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*NEWLINE can’t be the last reading*/223);
1491 osfree(style_name);
1492 osfree(new_order);
1493 return;
1496 if (style == STYLE_NOSURVEY) {
1497 if (TSTBIT(mUsed, Station)) {
1498 if (k >= kMac) {
1499 kMac = kMac * 2;
1500 new_order = osrealloc(new_order, kMac * sizeof(reading));
1502 new_order[k - 1] = Newline;
1503 new_order[k++] = End;
1505 } else if (style == STYLE_PASSAGE) {
1506 /* Station doesn't mean "multiline" for STYLE_PASSAGE. */
1507 } else if (!TSTBIT(mUsed, Newline) && (m_multi & mUsed)) {
1508 /* TRANSLATORS: Error given by something like:
1510 * *data normal station tape compass clino
1512 * ("station" signifies interleaved data). */
1513 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Interleaved readings, but no NEWLINE*/224);
1514 osfree(style_name);
1515 osfree(new_order);
1516 return;
1519 #if 0
1520 printf("mUsed = 0x%x\n", mUsed);
1521 #endif
1523 /* Check the supplied readings form a sufficient set. */
1524 if (style != STYLE_PASSAGE) {
1525 if ((mUsed & (BIT(Fr) | BIT(To))) == (BIT(Fr) | BIT(To)))
1526 mUsed |= BIT(Station);
1527 else if (TSTBIT(mUsed, Station))
1528 mUsed |= BIT(Fr) | BIT(To);
1531 if (mUsed & (BIT(Comp) | BIT(BackComp)))
1532 mUsed |= BIT(Comp) | BIT(BackComp);
1534 if (mUsed & (BIT(Clino) | BIT(BackClino)))
1535 mUsed |= BIT(Clino) | BIT(BackClino);
1537 if ((mUsed & (BIT(FrDepth) | BIT(ToDepth))) == (BIT(FrDepth) | BIT(ToDepth)))
1538 mUsed |= BIT(Depth) | BIT(DepthChange);
1539 else if (mUsed & (BIT(Depth) | BIT(DepthChange)))
1540 mUsed |= BIT(FrDepth) | BIT(ToDepth) | BIT(Depth) | BIT(DepthChange);
1542 if ((mUsed & (BIT(FrCount) | BIT(ToCount))) == (BIT(FrCount) | BIT(ToCount)))
1543 mUsed |= BIT(Count) | BIT(Tape) | BIT(BackTape);
1544 else if (mUsed & (BIT(Count) | BIT(Tape) | BIT(BackTape)))
1545 mUsed |= BIT(FrCount) | BIT(ToCount) | BIT(Count) | BIT(Tape) | BIT(BackTape);
1547 #if 0
1548 printf("mUsed = 0x%x, opt = 0x%x, mask = 0x%x\n", mUsed,
1549 mask_optional[style], mask[style]);
1550 #endif
1552 if (((mUsed &~ BIT(Newline)) | mask_optional[style]) != mask[style]) {
1553 /* Test should only fail with too few bits set, not too many */
1554 SVX_ASSERT((((mUsed &~ BIT(Newline)) | mask_optional[style])
1555 &~ mask[style]) == 0);
1556 /* TRANSLATORS: i.e. not enough readings for the style. */
1557 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Too few readings for data style “%s”*/64, style_name);
1558 osfree(style_name);
1559 osfree(new_order);
1560 return;
1563 /* don't free default ordering or ordering used by parent */
1564 if (pcs->ordering != default_order &&
1565 !(pcs->next && pcs->next->ordering == pcs->ordering))
1566 osfree((reading*)pcs->ordering);
1568 pcs->style = style;
1569 pcs->ordering = new_order;
1571 osfree(style_name);
1573 reinit_style:
1574 if (style == STYLE_PASSAGE) {
1575 lrudlist * new_psg = osnew(lrudlist);
1576 new_psg->tube = NULL;
1577 new_psg->next = model;
1578 model = new_psg;
1579 next_lrud = &(new_psg->tube);
1583 static void
1584 cmd_units(void)
1586 int units, quantity;
1587 unsigned long qmask;
1588 unsigned long m; /* mask with bit x set to indicate quantity x specified */
1589 real factor;
1590 filepos fp;
1592 qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1594 if (!qmask) return;
1595 if (qmask == BIT(Q_DEFAULT)) {
1596 default_units(pcs);
1597 return;
1600 get_pos(&fp);
1601 factor = read_numeric(fTrue);
1602 if (factor == 0.0) {
1603 set_pos(&fp);
1604 /* TRANSLATORS: error message given by "*units tape 0 feet" - it’s
1605 * meaningless to say your tape is marked in "0 feet" (but you might
1606 * measure distance by counting knots on a diving line, and tie them
1607 * every "2 feet"). */
1608 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /**UNITS factor must be non-zero*/200);
1609 skipline();
1610 return;
1613 units = get_units(qmask, fTrue);
1614 if (units == UNITS_NULL) return;
1615 if (TSTBIT(qmask, Q_GRADIENT))
1616 pcs->f_clino_percent = (units == UNITS_PERCENT);
1617 if (TSTBIT(qmask, Q_BACKGRADIENT))
1618 pcs->f_backclino_percent = (units == UNITS_PERCENT);
1620 if (TSTBIT(qmask, Q_BEARING)) {
1621 pcs->f_bearing_quadrants = (units == UNITS_QUADRANTS);
1623 if (TSTBIT(qmask, Q_BACKBEARING)) {
1624 pcs->f_backbearing_quadrants = (units == UNITS_QUADRANTS);
1627 if (factor == HUGE_REAL) {
1628 factor = factor_tab[units];
1629 } else {
1630 factor *= factor_tab[units];
1633 for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1634 if (qmask & m) pcs->units[quantity] = factor;
1637 static void
1638 cmd_calibrate(void)
1640 real sc, z;
1641 unsigned long qmask, m;
1642 int quantity;
1643 filepos fp;
1645 qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1646 if (!qmask) return; /* error already reported */
1648 if (qmask == BIT(Q_DEFAULT)) {
1649 default_calib(pcs);
1650 return;
1653 if (((qmask & LEN_QMASK)) && ((qmask & ANG_QMASK))) {
1654 /* TRANSLATORS: e.g.
1656 * *calibrate tape compass 1 1
1658 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Can’t calibrate angular and length quantities together*/227);
1659 return;
1662 z = read_numeric(fFalse);
1663 get_pos(&fp);
1664 sc = read_numeric(fTrue);
1665 if (sc == HUGE_REAL) {
1666 if (isalpha(ch)) {
1667 int units = get_units(qmask, fFalse);
1668 if (units == UNITS_NULL) {
1669 return;
1671 z *= factor_tab[units];
1672 sc = read_numeric(fTrue);
1673 if (sc == HUGE_REAL) {
1674 sc = (real)1.0;
1675 } else {
1676 /* Adjustment applied is: (reading - z) * sc
1677 * We want: reading * sc - z
1678 * So divide z by sc so the applied adjustment does what we want.
1680 z /= sc;
1682 } else {
1683 sc = (real)1.0;
1687 if (sc == HUGE_REAL) sc = (real)1.0;
1688 /* check for declination scale */
1689 if (TSTBIT(qmask, Q_DECLINATION) && sc != 1.0) {
1690 set_pos(&fp);
1691 /* TRANSLATORS: DECLINATION is a built-in keyword, so best not to
1692 * translate */
1693 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Scale factor must be 1.0 for DECLINATION*/40);
1694 skipline();
1695 return;
1697 if (sc == 0.0) {
1698 set_pos(&fp);
1699 /* TRANSLATORS: If the scale factor for an instrument is zero, then any
1700 * reading would be mapped to zero, which doesn't make sense. */
1701 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Scale factor must be non-zero*/391);
1702 skipline();
1703 return;
1705 for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1) {
1706 if (qmask & m) {
1707 pcs->z[quantity] = pcs->units[quantity] * z;
1708 pcs->sc[quantity] = sc;
1713 static void
1714 cmd_declination(void)
1716 real v = read_numeric(fTrue);
1717 if (v == HUGE_REAL) {
1718 get_token_no_blanks();
1719 if (strcmp(ucbuffer, "AUTO") != 0) {
1720 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_COL, /*Expected number or “AUTO”*/309);
1721 return;
1723 /* *declination auto X Y Z */
1724 real x = read_numeric(fFalse);
1725 real y = read_numeric(fFalse);
1726 real z = read_numeric(fFalse);
1727 if (!pcs->proj_str) {
1728 compile_diagnostic(DIAG_ERR, /*Input coordinate system must be specified for “*DECLINATION AUTO”*/301);
1729 return;
1731 /* Convert to WGS84 lat long. */
1732 PJ *transform = proj_create_crs_to_crs(PJ_DEFAULT_CTX,
1733 pcs->proj_str,
1734 WGS84_DATUM_STRING,
1735 NULL);
1736 if (transform) {
1737 /* Normalise the output order so x is longitude and y latitude - by
1738 * default new PROJ has them switched for EPSG:4326 which just seems
1739 * confusing.
1741 PJ* pj_norm = proj_normalize_for_visualization(PJ_DEFAULT_CTX,
1742 transform);
1743 proj_destroy(transform);
1744 transform = pj_norm;
1747 if (proj_angular_input(transform, PJ_FWD)) {
1748 /* Input coordinate system expects radians. */
1749 x = rad(x);
1750 y = rad(y);
1753 PJ_COORD coord = {{x, y, z, HUGE_VAL}};
1754 coord = proj_trans(transform, PJ_FWD, coord);
1755 x = coord.xyzt.x;
1756 y = coord.xyzt.y;
1757 z = coord.xyzt.z;
1759 if (x == HUGE_VAL || y == HUGE_VAL || z == HUGE_VAL) {
1760 compile_diagnostic(DIAG_ERR, /*Failed to convert coordinates: %s*/436,
1761 proj_errno_string(proj_errno(transform)));
1762 /* Set dummy values which are finite. */
1763 x = y = z = 0;
1765 proj_destroy(transform);
1766 double lon = rad(x);
1767 double lat = rad(y);
1768 pcs->z[Q_DECLINATION] = HUGE_REAL;
1769 pcs->dec_lat = lat;
1770 pcs->dec_lon = lon;
1771 pcs->dec_alt = z;
1772 /* Invalidate cached declination. */
1773 pcs->declination = HUGE_REAL;
1775 PJ *pj = proj_create(PJ_DEFAULT_CTX, proj_str_out);
1776 PJ_COORD lp;
1777 lp.lp.lam = lon;
1778 lp.lp.phi = lat;
1779 #if PROJ_VERSION_MAJOR < 8 || \
1780 (PROJ_VERSION_MAJOR == 8 && PROJ_VERSION_MINOR < 2)
1781 /* Code adapted from fix in PROJ 8.2.0 to make proj_factors() work in
1782 * cases we need (e.g. a CRS specified as "EPSG:<number>").
1784 switch (proj_get_type(pj)) {
1785 case PJ_TYPE_PROJECTED_CRS: {
1786 /* If it is a projected CRS, then compute the factors on the conversion
1787 * associated to it. We need to start from a temporary geographic CRS
1788 * using the same datum as the one of the projected CRS, and with
1789 * input coordinates being in longitude, latitude order in radian,
1790 * to be consistent with the expectations of the lp input parameter.
1793 PJ * geodetic_crs = proj_get_source_crs(PJ_DEFAULT_CTX, pj);
1794 if (!geodetic_crs)
1795 break;
1796 PJ * datum = proj_crs_get_datum(PJ_DEFAULT_CTX, geodetic_crs);
1797 #if PROJ_VERSION_MAJOR == 8 || \
1798 (PROJ_VERSION_MAJOR == 7 && PROJ_VERSION_MINOR >= 2)
1799 /* PROJ 7.2.0 upgraded to EPSG 10.x which added the concept
1800 * of a datum ensemble, and this version of PROJ also added
1801 * an API to deal with these.
1803 * If we're using PROJ < 7.2.0 then its EPSG database won't
1804 * have datum ensembles, so we don't need any code to handle
1805 * them.
1807 if (!datum) {
1808 datum = proj_crs_get_datum_ensemble(PJ_DEFAULT_CTX, geodetic_crs);
1810 #endif
1811 PJ * cs = proj_create_ellipsoidal_2D_cs(
1812 PJ_DEFAULT_CTX, PJ_ELLPS2D_LONGITUDE_LATITUDE, "Radian", 1.0);
1813 PJ * temp = proj_create_geographic_crs_from_datum(
1814 PJ_DEFAULT_CTX, "unnamed crs", datum, cs);
1815 proj_destroy(datum);
1816 proj_destroy(cs);
1817 proj_destroy(geodetic_crs);
1818 PJ * newOp = proj_create_crs_to_crs_from_pj(PJ_DEFAULT_CTX, temp, pj, NULL, NULL);
1819 proj_destroy(temp);
1820 if (!newOp) {
1821 break;
1823 proj_destroy(pj);
1824 pj = newOp;
1825 break;
1827 default:
1828 break;
1830 #endif
1831 PJ_FACTORS factors = proj_factors(pj, lp);
1832 pcs->convergence = factors.meridian_convergence;
1833 proj_destroy(pj);
1835 } else {
1836 /* *declination D UNITS */
1837 int units = get_units(BIT(Q_DECLINATION), fFalse);
1838 if (units == UNITS_NULL) {
1839 return;
1841 pcs->z[Q_DECLINATION] = -v * factor_tab[units];
1842 pcs->convergence = 0;
1846 #ifndef NO_DEPRECATED
1847 static void
1848 cmd_default(void)
1850 static const sztok defaulttab[] = {
1851 { "CALIBRATE", CMD_CALIBRATE },
1852 { "DATA", CMD_DATA },
1853 { "UNITS", CMD_UNITS },
1854 { NULL, CMD_NULL }
1856 static int default_depr_count = 0;
1858 if (default_depr_count < 5) {
1859 /* TRANSLATORS: If you're unsure what "deprecated" means, see:
1860 * https://en.wikipedia.org/wiki/Deprecation */
1861 compile_diagnostic(DIAG_WARN|DIAG_COL, /**DEFAULT is deprecated - use *CALIBRATE/DATA/SD/UNITS with argument DEFAULT instead*/20);
1862 if (++default_depr_count == 5)
1863 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
1866 get_token();
1867 switch (match_tok(defaulttab, TABSIZE(defaulttab))) {
1868 case CMD_CALIBRATE:
1869 default_calib(pcs);
1870 break;
1871 case CMD_DATA:
1872 default_style(pcs);
1873 default_grade(pcs);
1874 break;
1875 case CMD_UNITS:
1876 default_units(pcs);
1877 break;
1878 default:
1879 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown setting “%s”*/41, buffer);
1882 #endif
1884 static void
1885 cmd_include(void)
1887 char *pth, *fnm = NULL;
1888 int fnm_len;
1889 #ifndef NO_DEPRECATED
1890 prefix *root_store;
1891 #endif
1892 int ch_store;
1894 pth = path_from_fnm(file.filename);
1896 read_string(&fnm, &fnm_len);
1898 #ifndef NO_DEPRECATED
1899 /* Since *begin / *end nesting cannot cross file boundaries we only
1900 * need to preserve the prefix if the deprecated *prefix command
1901 * can be used */
1902 root_store = root;
1903 root = pcs->Prefix; /* Root for include file is current prefix */
1904 #endif
1905 ch_store = ch;
1907 data_file(pth, fnm);
1909 #ifndef NO_DEPRECATED
1910 root = root_store; /* and restore root */
1911 #endif
1912 ch = ch_store;
1914 s_free(&fnm);
1915 osfree(pth);
1918 static void
1919 cmd_sd(void)
1921 real sd, variance;
1922 int units;
1923 unsigned long qmask, m;
1924 int quantity;
1925 qmask = get_qlist(BIT(Q_DECLINATION));
1926 if (!qmask) return; /* no quantities found - error already reported */
1928 if (qmask == BIT(Q_DEFAULT)) {
1929 default_grade(pcs);
1930 return;
1932 sd = read_numeric(fFalse);
1933 if (sd <= (real)0.0) {
1934 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_COL, /*Standard deviation must be positive*/48);
1935 return;
1937 units = get_units(qmask, fFalse);
1938 if (units == UNITS_NULL) return;
1940 sd *= factor_tab[units];
1941 variance = sqrd(sd);
1943 for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1944 if (qmask & m) pcs->Var[quantity] = variance;
1947 static void
1948 cmd_title(void)
1950 if (!fExplicitTitle && pcs->Prefix == root) {
1951 /* If we don't have an explicit title yet, and we're currently in the
1952 * root prefix, use this title explicitly. */
1953 fExplicitTitle = fTrue;
1954 read_string(&survey_title, &survey_title_len);
1955 } else {
1956 /* parse and throw away this title (but still check rest of line) */
1957 char *s = NULL;
1958 int len;
1959 read_string(&s, &len);
1960 s_free(&s);
1964 static const sztok case_tab[] = {
1965 {"PRESERVE", OFF},
1966 {"TOLOWER", LOWER},
1967 {"TOUPPER", UPPER},
1968 {NULL, -1}
1971 static void
1972 cmd_case(void)
1974 int setting;
1975 get_token();
1976 setting = match_tok(case_tab, TABSIZE(case_tab));
1977 if (setting != -1) {
1978 pcs->Case = setting;
1979 } else {
1980 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Found “%s”, expecting “PRESERVE”, “TOUPPER”, or “TOLOWER”*/10, buffer);
1984 typedef enum {
1985 CS_NONE = -1,
1986 CS_CUSTOM,
1987 CS_EPSG,
1988 CS_ESRI,
1989 CS_EUR,
1990 CS_IJTSK,
1991 CS_JTSK,
1992 CS_LAT,
1993 CS_LOCAL,
1994 CS_LONG,
1995 CS_OSGB,
1996 CS_S_MERC,
1997 CS_UTM
1998 } cs_class;
2000 static const sztok cs_tab[] = {
2001 {"CUSTOM", CS_CUSTOM},
2002 {"EPSG", CS_EPSG}, /* EPSG:<number> */
2003 {"ESRI", CS_ESRI}, /* ESRI:<number> */
2004 {"EUR", CS_EUR}, /* EUR79Z30 */
2005 {"IJTSK", CS_IJTSK}, /* IJTSK or IJTSK03 */
2006 {"JTSK", CS_JTSK}, /* JTSK or JTSK03 */
2007 {"LAT", CS_LAT}, /* LAT-LONG */
2008 {"LOCAL", CS_LOCAL},
2009 {"LONG", CS_LONG}, /* LONG-LAT */
2010 {"OSGB", CS_OSGB}, /* OSGB:<H, N, O, S or T><A-Z except I> */
2011 {"S", CS_S_MERC}, /* S-MERC */
2012 {"UTM", CS_UTM}, /* UTM<zone><N or S or nothing> */
2013 {NULL, CS_NONE}
2016 static void
2017 cmd_cs(void)
2019 char * proj_str = NULL;
2020 int proj_str_len;
2021 cs_class cs;
2022 int cs_sub = INT_MIN;
2023 filepos fp;
2024 bool output = fFalse;
2025 enum { YES, NO, MAYBE } ok_for_output = YES;
2026 static bool had_cs = fFalse;
2028 if (!had_cs) {
2029 had_cs = fTrue;
2030 if (first_fix_name) {
2031 compile_diagnostic_at(DIAG_ERR,
2032 first_fix_filename, first_fix_line,
2033 /*Station “%s” fixed before CS command first used*/442,
2034 sprint_prefix(first_fix_name));
2038 get_pos(&fp);
2039 /* Note get_token() only accepts letters - it'll stop at digits so "UTM12"
2040 * will give token "UTM". */
2041 get_token();
2042 if (strcmp(ucbuffer, "OUT") == 0) {
2043 output = fTrue;
2044 get_pos(&fp);
2045 get_token();
2047 cs = match_tok(cs_tab, TABSIZE(cs_tab));
2048 switch (cs) {
2049 case CS_NONE:
2050 break;
2051 case CS_CUSTOM:
2052 ok_for_output = MAYBE;
2053 get_pos(&fp);
2054 read_string(&proj_str, &proj_str_len);
2055 cs_sub = 0;
2056 break;
2057 case CS_EPSG: case CS_ESRI:
2058 ok_for_output = MAYBE;
2059 if (ch == ':' && isdigit(nextch())) {
2060 unsigned n = read_uint();
2061 if (n < 1000000) {
2062 cs_sub = (int)n;
2065 break;
2066 case CS_EUR:
2067 if (isdigit(ch) &&
2068 read_uint() == 79 &&
2069 (ch == 'Z' || ch == 'z') &&
2070 isdigit(nextch()) &&
2071 read_uint() == 30) {
2072 cs_sub = 7930;
2074 break;
2075 case CS_JTSK:
2076 ok_for_output = NO;
2077 /* FALLTHRU */
2078 case CS_IJTSK:
2079 if (ch == '0') {
2080 if (nextch() == '3') {
2081 nextch();
2082 cs_sub = 3;
2084 } else {
2085 cs_sub = 0;
2087 break;
2088 case CS_LAT: case CS_LONG:
2089 ok_for_output = NO;
2090 if (ch == '-') {
2091 nextch();
2092 get_token_no_blanks();
2093 cs_class cs2 = match_tok(cs_tab, TABSIZE(cs_tab));
2094 if ((cs ^ cs2) == (CS_LAT ^ CS_LONG)) {
2095 cs_sub = 0;
2098 break;
2099 case CS_LOCAL:
2100 cs_sub = 0;
2101 break;
2102 case CS_OSGB:
2103 if (ch == ':') {
2104 int uch1 = toupper(nextch());
2105 if (strchr("HNOST", uch1)) {
2106 int uch2 = toupper(nextch());
2107 if (uch2 >= 'A' && uch2 <= 'Z' && uch2 != 'I') {
2108 int x, y;
2109 nextch();
2110 if (uch1 > 'I') --uch1;
2111 uch1 -= 'A';
2112 if (uch2 > 'I') --uch2;
2113 uch2 -= 'A';
2114 x = uch1 % 5;
2115 y = uch1 / 5;
2116 x = (x * 5) + uch2 % 5;
2117 y = (y * 5) + uch2 / 5;
2118 cs_sub = y * 25 + x;
2122 break;
2123 case CS_S_MERC:
2124 if (ch == '-') {
2125 nextch();
2126 get_token_no_blanks();
2127 if (strcmp(ucbuffer, "MERC") == 0) {
2128 cs_sub = 0;
2131 break;
2132 case CS_UTM:
2133 if (isdigit(ch)) {
2134 unsigned n = read_uint();
2135 if (n >= 1 && n <= 60) {
2136 int uch = toupper(ch);
2137 cs_sub = (int)n;
2138 if (uch == 'S') {
2139 nextch();
2140 cs_sub = -cs_sub;
2141 } else if (uch == 'N') {
2142 nextch();
2146 break;
2148 if (cs_sub == INT_MIN || isalnum(ch)) {
2149 set_pos(&fp);
2150 compile_diagnostic(DIAG_ERR|DIAG_STRING, /*Unknown coordinate system*/434);
2151 skipline();
2152 return;
2154 /* Actually handle the cs */
2155 switch (cs) {
2156 case CS_NONE:
2157 break;
2158 case CS_CUSTOM:
2159 /* proj_str already set */
2160 break;
2161 case CS_EPSG:
2162 proj_str = osmalloc(32);
2163 sprintf(proj_str, "EPSG:%d", cs_sub);
2164 break;
2165 case CS_ESRI:
2166 proj_str = osmalloc(32);
2167 sprintf(proj_str, "ESRI:%d", cs_sub);
2168 break;
2169 case CS_EUR:
2170 proj_str = osstrdup("+proj=utm +zone=30 +ellps=intl +towgs84=-86,-98,-119,0,0,0,0 +no_defs");
2171 break;
2172 case CS_IJTSK:
2173 if (cs_sub == 0)
2174 proj_str = osstrdup("+proj=krovak +ellps=bessel +towgs84=570.8285,85.6769,462.842,4.9984,1.5867,5.2611,3.5623 +no_defs");
2175 else
2176 proj_str = osstrdup("+proj=krovak +ellps=bessel +towgs84=485.021,169.465,483.839,7.786342,4.397554,4.102655,0 +no_defs");
2177 break;
2178 case CS_JTSK:
2179 if (cs_sub == 0)
2180 proj_str = osstrdup("+proj=krovak +czech +ellps=bessel +towgs84=570.8285,85.6769,462.842,4.9984,1.5867,5.2611,3.5623 +no_defs");
2181 else
2182 proj_str = osstrdup("+proj=krovak +czech +ellps=bessel +towgs84=485.021,169.465,483.839,7.786342,4.397554,4.102655,0 +no_defs");
2183 break;
2184 case CS_LAT:
2185 /* FIXME: Requires PROJ >= 4.8.0 for +axis, and the SDs will be
2186 * misapplied, so we may want to swap ourselves. Also, while
2187 * therion supports lat-long, I'm not totally convinced that it is
2188 * sensible to do so - people often say "lat-long", but probably
2189 * don't think that that's actually "Northing, Easting". This
2190 * seems like it'll result in people accidentally getting X and Y
2191 * swapped in their fixed points...
2193 #if 0
2194 proj_str = osstrdup("+proj=longlat +ellps=WGS84 +datum=WGS84 +axis=neu +no_defs");
2195 #endif
2196 break;
2197 case CS_LOCAL:
2198 /* FIXME: Is it useful to be able to explicitly specify this? */
2199 break;
2200 case CS_LONG:
2201 proj_str = osstrdup("EPSG:4326");
2202 break;
2203 case CS_OSGB: {
2204 int x = 14 - (cs_sub % 25);
2205 int y = (cs_sub / 25) - 20;
2206 proj_str = osmalloc(160);
2207 sprintf(proj_str, "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=%d +y_0=%d +ellps=airy +datum=OSGB36 +units=m +no_defs", x * 100000, y * 100000);
2208 break;
2210 case CS_S_MERC:
2211 proj_str = osstrdup("EPSG:3857");
2212 break;
2213 case CS_UTM:
2214 proj_str = osmalloc(32);
2215 if (cs_sub > 0) {
2216 sprintf(proj_str, "EPSG:%d", 32600 + cs_sub);
2217 } else {
2218 sprintf(proj_str, "EPSG:%d", 32700 - cs_sub);
2220 break;
2223 if (!proj_str) {
2224 /* printf("CS %d:%d\n", (int)cs, cs_sub); */
2225 set_pos(&fp);
2226 compile_diagnostic(DIAG_ERR|DIAG_STRING, /*Unknown coordinate system*/434);
2227 skipline();
2228 return;
2231 if (output) {
2232 if (ok_for_output == NO) {
2233 set_pos(&fp);
2234 compile_diagnostic(DIAG_ERR|DIAG_STRING, /*Coordinate system unsuitable for output*/435);
2235 skipline();
2236 return;
2239 if (proj_str_out && strcmp(proj_str, proj_str_out) == 0) {
2240 /* Same as the output cs that's already set, so nothing to do. */
2241 osfree(proj_str);
2242 return;
2245 if (ok_for_output == MAYBE) {
2246 /* We only actually create the transformation from input to output when
2247 * we need it, but for a custom proj string or EPSG/ESRI code we need
2248 * to check that the specified coordinate system is valid and also if
2249 * it's suitable for output so we need to test creating it here.
2251 PJ* pj = proj_create(PJ_DEFAULT_CTX, proj_str);
2252 if (!pj) {
2253 set_pos(&fp);
2254 compile_diagnostic(DIAG_ERR|DIAG_STRING, /*Invalid coordinate system: %s*/443,
2255 proj_errno_string(proj_context_errno(PJ_DEFAULT_CTX)));
2256 skipline();
2257 osfree(proj_str);
2258 return;
2260 int type = proj_get_type(pj);
2261 if (type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
2262 type == PJ_TYPE_GEOGRAPHIC_3D_CRS) {
2263 set_pos(&fp);
2264 compile_diagnostic(DIAG_ERR|DIAG_STRING, /*Coordinate system unsuitable for output*/435);
2265 skipline();
2266 osfree(proj_str);
2267 return;
2271 if (proj_str_out) {
2272 /* If the output cs is already set, subsequent attempts to set it
2273 * are silently ignored (so you can combine two datasets and set
2274 * the output cs to use before you include either).
2276 osfree(proj_str);
2277 } else {
2278 proj_str_out = proj_str;
2280 } else {
2281 if (proj_str_out && strcmp(proj_str, proj_str_out) == 0) {
2282 /* Same as the current output projection, so valid for input. */
2283 } else if (pcs->proj_str && strcmp(proj_str, pcs->proj_str) == 0) {
2284 /* Same as the current input projection, so nothing to do! */
2285 return;
2286 } else if (ok_for_output == MAYBE) {
2287 /* (ok_for_output == MAYBE) also happens to indicate whether we need
2288 * to check that the coordinate system is valid for input.
2290 PJ* pj = proj_create(PJ_DEFAULT_CTX, proj_str);
2291 if (!pj) {
2292 set_pos(&fp);
2293 compile_diagnostic(DIAG_ERR|DIAG_STRING, /*Invalid coordinate system: %s*/443,
2294 proj_errno_string(proj_context_errno(PJ_DEFAULT_CTX)));
2295 skipline();
2296 return;
2298 proj_destroy(pj);
2301 /* Free current input proj_str if not used by parent. */
2302 settings * p = pcs;
2303 if (!p->next || p->proj_str != p->next->proj_str)
2304 osfree(p->proj_str);
2305 p->proj_str = proj_str;
2306 invalidate_pj_cached();
2310 static const sztok infer_tab[] = {
2311 { "EQUATES", INFER_EQUATES },
2312 { "EXPORTS", INFER_EXPORTS },
2313 { "PLUMBS", INFER_PLUMBS },
2314 #if 0 /* FIXME */
2315 { "SUBSURVEYS", INFER_SUBSURVEYS },
2316 #endif
2317 { NULL, INFER_NULL }
2320 static const sztok onoff_tab[] = {
2321 { "OFF", 0 },
2322 { "ON", 1 },
2323 { NULL, -1 }
2326 static void
2327 cmd_infer(void)
2329 infer_what setting;
2330 int on;
2331 get_token();
2332 setting = match_tok(infer_tab, TABSIZE(infer_tab));
2333 if (setting == INFER_NULL) {
2334 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Found “%s”, expecting “EQUATES”, “EXPORTS”, or “PLUMBS”*/31, buffer);
2335 return;
2337 get_token();
2338 on = match_tok(onoff_tab, TABSIZE(onoff_tab));
2339 if (on == -1) {
2340 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Found “%s”, expecting “ON” or “OFF”*/32, buffer);
2341 return;
2344 if (on) {
2345 pcs->infer |= BIT(setting);
2346 if (setting == INFER_EXPORTS) fExportUsed = fTrue;
2347 } else {
2348 pcs->infer &= ~BIT(setting);
2352 static void
2353 cmd_truncate(void)
2355 unsigned int truncate_at = 0; /* default is no truncation */
2356 filepos fp;
2358 get_pos(&fp);
2360 get_token();
2361 if (strcmp(ucbuffer, "OFF") != 0) {
2362 if (*ucbuffer) set_pos(&fp);
2363 truncate_at = read_uint();
2365 /* for backward compatibility, "*truncate 0" means "*truncate off" */
2366 pcs->Truncate = (truncate_at == 0) ? INT_MAX : truncate_at;
2369 static void
2370 cmd_ref(void)
2372 /* Just syntax check for now. */
2373 char *ref = NULL;
2374 int ref_len;
2375 read_string(&ref, &ref_len);
2376 s_free(&ref);
2379 static void
2380 cmd_require(void)
2382 const unsigned int version[] = {COMMAVERSION};
2383 const unsigned int *ver = version;
2384 filepos fp;
2386 skipblanks();
2387 get_pos(&fp);
2388 while (1) {
2389 int diff = *ver++ - read_uint();
2390 if (diff > 0) break;
2391 if (diff < 0) {
2392 size_t i, len;
2393 char *v;
2394 filepos fp_tmp;
2396 /* find end of version number */
2397 while (isdigit(ch) || ch == '.') nextch();
2398 get_pos(&fp_tmp);
2399 len = (size_t)(fp_tmp.offset - fp.offset);
2400 v = osmalloc(len + 1);
2401 set_pos(&fp);
2402 for (i = 0; i < len; i++) {
2403 v[i] = ch;
2404 nextch();
2406 v[i] = '\0';
2407 /* TRANSLATORS: Feel free to translate as "or newer" instead of "or
2408 * greater" if that gives a more natural translation. It's
2409 * technically not quite right when there are parallel active release
2410 * series (e.g. Survex 1.0.40 was released *after* 1.2.0), but this
2411 * seems unlikely to confuse users. "Survex" is the name of the
2412 * software, so should not be translated.
2414 * Here "survey" is a "cave map" rather than list of questions - it should be
2415 * translated to the terminology that cavers using the language would use.
2417 fatalerror_in_file(file.filename, file.line, /*Survex version %s or greater required to process this survey data.*/2, v);
2419 if (ch != '.') break;
2420 nextch();
2421 if (!isdigit(ch) || ver == version + sizeof(version) / sizeof(*version))
2422 break;
2424 /* skip rest of version number */
2425 while (isdigit(ch) || ch == '.') nextch();
2428 /* allocate new meta_data if need be */
2429 void
2430 copy_on_write_meta(settings *s)
2432 if (!s->meta || s->meta->ref_count != 0) {
2433 meta_data * meta_new = osnew(meta_data);
2434 if (!s->meta) {
2435 meta_new->days1 = meta_new->days2 = -1;
2436 } else {
2437 *meta_new = *(s->meta);
2439 meta_new->ref_count = 0;
2440 s->meta = meta_new;
2444 static void
2445 cmd_date(void)
2447 int year, month, day;
2448 int days1, days2;
2449 bool implicit_range = fFalse;
2450 filepos fp, fp2;
2452 get_pos(&fp);
2453 read_date(&year, &month, &day);
2454 days1 = days_since_1900(year, month ? month : 1, day ? day : 1);
2456 if (days1 > current_days_since_1900) {
2457 set_pos(&fp);
2458 compile_diagnostic(DIAG_WARN|DIAG_DATE, /*Date is in the future!*/80);
2461 skipblanks();
2462 if (ch == '-') {
2463 nextch();
2464 get_pos(&fp2);
2465 read_date(&year, &month, &day);
2466 } else {
2467 if (month && day) {
2468 days2 = days1;
2469 goto read;
2471 implicit_range = fTrue;
2474 if (month == 0) month = 12;
2475 if (day == 0) day = last_day(year, month);
2476 days2 = days_since_1900(year, month, day);
2478 if (!implicit_range && days2 > current_days_since_1900) {
2479 set_pos(&fp2);
2480 compile_diagnostic(DIAG_WARN|DIAG_DATE, /*Date is in the future!*/80);
2483 if (days2 < days1) {
2484 set_pos(&fp);
2485 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*End of date range is before the start*/81);
2486 int tmp = days1;
2487 days1 = days2;
2488 days2 = tmp;
2491 read:
2492 if (!pcs->meta || pcs->meta->days1 != days1 || pcs->meta->days2 != days2) {
2493 copy_on_write_meta(pcs);
2494 pcs->meta->days1 = days1;
2495 pcs->meta->days2 = days2;
2496 /* Invalidate cached declination. */
2497 pcs->declination = HUGE_REAL;
2501 typedef void (*cmd_fn)(void);
2503 static const cmd_fn cmd_funcs[] = {
2504 cmd_alias,
2505 cmd_begin,
2506 cmd_calibrate,
2507 cmd_case,
2508 skipline, /*cmd_copyright,*/
2509 cmd_cs,
2510 cmd_data,
2511 cmd_date,
2512 cmd_declination,
2513 #ifndef NO_DEPRECATED
2514 cmd_default,
2515 #endif
2516 cmd_end,
2517 cmd_entrance,
2518 cmd_equate,
2519 cmd_export,
2520 cmd_fix,
2521 cmd_flags,
2522 cmd_include,
2523 cmd_infer,
2524 skipline, /*cmd_instrument,*/
2525 #ifndef NO_DEPRECATED
2526 cmd_prefix,
2527 #endif
2528 cmd_ref,
2529 cmd_require,
2530 cmd_sd,
2531 cmd_set,
2532 solve_network,
2533 skipline, /*cmd_team,*/
2534 cmd_title,
2535 cmd_truncate,
2536 cmd_units
2539 extern void
2540 handle_command(void)
2542 int cmdtok;
2543 get_token();
2544 cmdtok = match_tok(cmd_tab, TABSIZE(cmd_tab));
2546 if (cmdtok < 0 || cmdtok >= (int)(sizeof(cmd_funcs) / sizeof(cmd_fn))) {
2547 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown command “%s”*/12, buffer);
2548 return;
2551 switch (cmdtok) {
2552 case CMD_EXPORT:
2553 if (!f_export_ok)
2554 /* TRANSLATORS: The *EXPORT command is only valid just after *BEGIN
2555 * <SURVEY>, so this would generate this error:
2557 * *begin fred
2558 * 1 2 1.23 045 -6
2559 * *export 2
2560 * *end fred */
2561 compile_diagnostic(DIAG_ERR, /**EXPORT must immediately follow “*BEGIN <SURVEY>”*/57);
2562 break;
2563 case CMD_ALIAS:
2564 case CMD_CALIBRATE:
2565 case CMD_CASE:
2566 case CMD_COPYRIGHT:
2567 case CMD_CS:
2568 case CMD_DATA:
2569 case CMD_DATE:
2570 case CMD_DECLINATION:
2571 case CMD_DEFAULT:
2572 case CMD_FLAGS:
2573 case CMD_INFER:
2574 case CMD_INSTRUMENT:
2575 case CMD_REF:
2576 case CMD_REQUIRE:
2577 case CMD_SD:
2578 case CMD_SET:
2579 case CMD_TEAM:
2580 case CMD_TITLE:
2581 case CMD_TRUNCATE:
2582 case CMD_UNITS:
2583 /* These can occur between *begin and *export */
2584 break;
2585 default:
2586 /* NB: additional handling for "*begin <survey>" in cmd_begin */
2587 f_export_ok = fFalse;
2588 break;
2591 cmd_funcs[cmdtok]();