Adapt proj_factors() patch from proj 8.2.0
[survex.git] / src / commands.c
blob3d08ab2a844dc2ff805d98ffc39672fe6e686b41
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 extern void
709 free_settings(settings *p) {
710 /* don't free default ordering or ordering used by parent */
711 const reading *order = p->ordering;
712 if (order != default_order && (!p->next || order != p->next->ordering))
713 osfree((reading*)order);
715 /* free Translate if not used by parent */
716 if (!p->next || p->Translate != p->next->Translate)
717 osfree(p->Translate - 1);
719 /* free meta if not used by parent, or in this block */
720 if (p->meta && (!p->next || p->meta != p->next->meta) && p->meta->ref_count == 0)
721 osfree(p->meta);
723 /* free proj_str if not used by parent, or as the output projection */
724 if (p->proj_str &&
725 (!p->next || p->proj_str != p->next->proj_str) &&
726 p->proj_str != proj_str_out) {
727 osfree(p->proj_str);
730 osfree(p);
733 static void
734 cmd_end(void)
736 settings *pcsParent;
737 prefix *survey, *begin_survey;
738 filepos fp;
740 pcsParent = pcs->next;
742 if (pcs->begin_lineno == 0) {
743 if (pcsParent == NULL) {
744 /* more ENDs than BEGINs */
745 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*No matching BEGIN*/192);
746 } else {
747 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*END with no matching BEGIN in this file*/22);
749 return;
752 begin_survey = pcs->begin_survey;
754 SVX_ASSERT(pcsParent);
755 free_settings(pcs);
756 pcs = pcsParent;
758 /* note need to read using root *before* BEGIN */
759 skipblanks();
760 if (isEol(ch) || isComm(ch)) {
761 survey = NULL;
762 } else {
763 get_pos(&fp);
764 survey = read_prefix(PFX_SURVEY|PFX_ALLOW_ROOT);
767 if (survey != begin_survey) {
768 if (survey) {
769 set_pos(&fp);
770 if (!begin_survey) {
771 /* TRANSLATORS: Used when a BEGIN command has no survey, but the
772 * END command does, e.g.:
774 * *begin
775 * 1 2 10.00 178 -01
776 * *end entrance <--[Message given here] */
777 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Matching BEGIN command has no survey name*/36);
778 } else {
779 /* TRANSLATORS: *BEGIN <survey> and *END <survey> should have the
780 * same <survey> if it’s given at all */
781 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Survey name doesn’t match BEGIN*/193);
783 skipline();
784 } else {
785 /* TRANSLATORS: Used when a BEGIN command has a survey name, but the
786 * END command omits it, e.g.:
788 * *begin entrance
789 * 1 2 10.00 178 -01
790 * *end <--[Message given here] */
791 compile_diagnostic(DIAG_WARN|DIAG_COL, /*Survey name omitted from END*/194);
796 static void
797 cmd_entrance(void)
799 prefix *pfx = read_prefix(PFX_STATION);
800 pfx->sflags |= BIT(SFLAGS_ENTRANCE);
803 static const prefix * first_fix_name = NULL;
804 static const char * first_fix_filename;
805 static unsigned first_fix_line;
807 static void
808 cmd_fix(void)
810 prefix *fix_name;
811 node *stn = NULL;
812 static prefix *name_omit_already = NULL;
813 static const char * name_omit_already_filename = NULL;
814 static unsigned int name_omit_already_line;
815 real x, y, z;
816 filepos fp;
818 fix_name = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
819 fix_name->sflags |= BIT(SFLAGS_FIXED);
821 get_pos(&fp);
822 get_token();
823 if (strcmp(ucbuffer, "REFERENCE") == 0) {
824 /* suppress "unused fixed point" warnings for this station */
825 fix_name->sflags |= BIT(SFLAGS_USED);
826 } else {
827 if (*ucbuffer) set_pos(&fp);
830 x = read_numeric(fTrue);
831 if (x == HUGE_REAL) {
832 /* If the end of the line isn't blank, read a number after all to
833 * get a more helpful error message */
834 if (!isEol(ch) && !isComm(ch)) x = read_numeric(fFalse);
836 if (x == HUGE_REAL) {
837 if (pcs->proj_str || proj_str_out) {
838 compile_diagnostic(DIAG_ERR|DIAG_COL|DIAG_SKIP, /*Coordinates can't be omitted when coordinate system has been specified*/439);
839 return;
842 if (fix_name == name_omit_already) {
843 compile_diagnostic(DIAG_WARN|DIAG_COL, /*Same station fixed twice with no coordinates*/61);
844 return;
847 /* TRANSLATORS: " *fix a " gives this message: */
848 compile_diagnostic(DIAG_WARN|DIAG_COL, /*FIX command with no coordinates - fixing at (0,0,0)*/54);
850 if (name_omit_already) {
851 /* TRANSLATORS: Emitted after second and subsequent "FIX command with
852 * no coordinates - fixing at (0,0,0)" warnings.
854 compile_diagnostic_at(DIAG_ERR|DIAG_COL,
855 name_omit_already_filename,
856 name_omit_already_line,
857 /*Already had FIX command with no coordinates for station “%s”*/441,
858 sprint_prefix(name_omit_already));
859 } else {
860 name_omit_already = fix_name;
861 name_omit_already_filename = file.filename;
862 name_omit_already_line = file.line;
865 x = y = z = (real)0.0;
866 } else {
867 real sdx;
868 y = read_numeric(fFalse);
869 z = read_numeric(fFalse);
871 if (pcs->proj_str && proj_str_out) {
872 PJ *transform = proj_create_crs_to_crs(PJ_DEFAULT_CTX,
873 pcs->proj_str,
874 proj_str_out,
875 NULL);
876 if (transform) {
877 // Normalise the output order so x is longitude and y latitude - by
878 // default new PROJ has them switched for EPSG:4326 which just seems
879 // confusing.
880 PJ* pj_norm = proj_normalize_for_visualization(PJ_DEFAULT_CTX,
881 transform);
882 proj_destroy(transform);
883 transform = pj_norm;
886 if (proj_angular_input(transform, PJ_FWD)) {
887 /* Input coordinate system expects radians. */
888 x = rad(x);
889 y = rad(y);
892 PJ_COORD coord = {{x, y, z, HUGE_VAL}};
893 coord = proj_trans(transform, PJ_FWD, coord);
894 x = coord.xyzt.x;
895 y = coord.xyzt.y;
896 z = coord.xyzt.z;
898 if (x == HUGE_VAL || y == HUGE_VAL || z == HUGE_VAL) {
899 compile_diagnostic(DIAG_ERR, /*Failed to convert coordinates: %s*/436,
900 proj_errno_string(proj_errno(transform)));
901 // Set dummy values which are finite.
902 x = y = z = 0;
904 proj_destroy(transform);
905 } else if (pcs->proj_str) {
906 compile_diagnostic(DIAG_ERR, /*The input projection is set but the output projection isn't*/437);
907 } else if (proj_str_out) {
908 compile_diagnostic(DIAG_ERR, /*The output projection is set but the input projection isn't*/438);
911 get_pos(&fp);
912 sdx = read_numeric(fTrue);
913 if (sdx <= 0) {
914 set_pos(&fp);
915 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_NUM, /*Standard deviation must be positive*/48);
916 return;
918 if (sdx != HUGE_REAL) {
919 real sdy, sdz;
920 real cxy = 0, cyz = 0, czx = 0;
921 get_pos(&fp);
922 sdy = read_numeric(fTrue);
923 if (sdy == HUGE_REAL) {
924 /* only one variance given */
925 sdy = sdz = sdx;
926 } else {
927 if (sdy <= 0) {
928 set_pos(&fp);
929 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_NUM, /*Standard deviation must be positive*/48);
930 return;
932 get_pos(&fp);
933 sdz = read_numeric(fTrue);
934 if (sdz == HUGE_REAL) {
935 /* two variances given - horizontal & vertical */
936 sdz = sdy;
937 sdy = sdx;
938 } else {
939 if (sdz <= 0) {
940 set_pos(&fp);
941 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_NUM, /*Standard deviation must be positive*/48);
942 return;
944 cxy = read_numeric(fTrue);
945 if (cxy != HUGE_REAL) {
946 /* covariances given */
947 cyz = read_numeric(fFalse);
948 czx = read_numeric(fFalse);
949 } else {
950 cxy = 0;
954 stn = StnFromPfx(fix_name);
955 if (!fixed(stn)) {
956 node *fixpt = osnew(node);
957 prefix *name;
958 name = osnew(prefix);
959 name->pos = osnew(pos);
960 name->ident = NULL;
961 name->shape = 0;
962 fixpt->name = name;
963 name->stn = fixpt;
964 name->up = NULL;
965 if (TSTBIT(pcs->infer, INFER_EXPORTS)) {
966 name->min_export = USHRT_MAX;
967 } else {
968 name->min_export = 0;
970 name->max_export = 0;
971 name->sflags = 0;
972 add_stn_to_list(&stnlist, fixpt);
973 POS(fixpt, 0) = x;
974 POS(fixpt, 1) = y;
975 POS(fixpt, 2) = z;
976 fix(fixpt);
977 fixpt->leg[0] = fixpt->leg[1] = fixpt->leg[2] = NULL;
978 addfakeleg(fixpt, stn, 0, 0, 0,
979 sdx * sdx, sdy * sdy, sdz * sdz
980 #ifndef NO_COVARIANCES
981 , cxy, cyz, czx
982 #endif
986 if (!first_fix_name) {
987 /* We track if we've fixed a station yet, and if so what the name
988 * of the first fix was, so that we can issue an error if the
989 * output coordinate system is set after fixing a station. */
990 first_fix_name = fix_name;
991 first_fix_filename = file.filename;
992 first_fix_line = file.line;
995 return;
999 if (!first_fix_name) {
1000 /* We track if we've fixed a station yet, and if so what the name of the
1001 * first fix was, so that we can issue an error if the output coordinate
1002 * system is set after fixing a station. */
1003 first_fix_name = fix_name;
1004 first_fix_filename = file.filename;
1005 first_fix_line = file.line;
1008 stn = StnFromPfx(fix_name);
1009 if (!fixed(stn)) {
1010 POS(stn, 0) = x;
1011 POS(stn, 1) = y;
1012 POS(stn, 2) = z;
1013 fix(stn);
1014 return;
1017 if (x != POS(stn, 0) || y != POS(stn, 1) || z != POS(stn, 2)) {
1018 compile_diagnostic(DIAG_ERR, /*Station already fixed or equated to a fixed point*/46);
1019 return;
1021 /* TRANSLATORS: *fix a 1 2 3 / *fix a 1 2 3 */
1022 compile_diagnostic(DIAG_WARN, /*Station already fixed at the same coordinates*/55);
1025 static void
1026 cmd_flags(void)
1028 static const sztok flagtab[] = {
1029 {"DUPLICATE", FLAGS_DUPLICATE },
1030 {"NOT", FLAGS_NOT },
1031 {"SPLAY", FLAGS_SPLAY },
1032 {"SURFACE", FLAGS_SURFACE },
1033 {NULL, FLAGS_UNKNOWN }
1035 bool fNot = fFalse;
1036 bool fEmpty = fTrue;
1037 while (1) {
1038 int flag;
1039 get_token();
1040 /* If buffer is empty, it could mean end of line, or maybe
1041 * some non-letter junk which is better reported later */
1042 if (!buffer[0]) break;
1044 fEmpty = fFalse;
1045 flag = match_tok(flagtab, TABSIZE(flagtab));
1046 /* treat the second NOT in "NOT NOT" as an unknown flag */
1047 if (flag == FLAGS_UNKNOWN || (fNot && flag == FLAGS_NOT)) {
1048 compile_diagnostic(DIAG_ERR|DIAG_BUF, /*FLAG “%s” unknown*/68, buffer);
1049 /* Recover from “*FLAGS NOT BOGUS SURFACE” by ignoring "NOT BOGUS" */
1050 fNot = fFalse;
1051 } else if (flag == FLAGS_NOT) {
1052 fNot = fTrue;
1053 } else if (fNot) {
1054 pcs->flags &= ~BIT(flag);
1055 fNot = fFalse;
1056 } else {
1057 pcs->flags |= BIT(flag);
1061 if (fNot) {
1062 compile_diagnostic(DIAG_ERR|DIAG_BUF, /*Expecting “DUPLICATE”, “SPLAY”, or “SURFACE”*/188);
1063 } else if (fEmpty) {
1064 compile_diagnostic(DIAG_ERR|DIAG_BUF, /*Expecting “NOT”, “DUPLICATE”, “SPLAY”, or “SURFACE”*/189);
1068 static void
1069 cmd_equate(void)
1071 prefix *name1, *name2;
1072 bool fOnlyOneStn = fTrue; /* to trap eg *equate entrance.6 */
1073 filepos fp;
1075 get_pos(&fp);
1076 name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO);
1077 while (fTrue) {
1078 name2 = name1;
1079 skipblanks();
1080 if (isEol(ch) || isComm(ch)) {
1081 if (fOnlyOneStn) {
1082 set_pos(&fp);
1083 /* TRANSLATORS: EQUATE is a command name, so shouldn’t be
1084 * translated.
1086 * Here "station" is a survey station, not a train station.
1088 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_TOKEN, /*Only one station in EQUATE command*/33);
1090 return;
1093 name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO);
1094 process_equate(name1, name2);
1095 fOnlyOneStn = fFalse;
1099 static void
1100 report_missing_export(prefix *pfx, int depth)
1102 char *s;
1103 const char *p;
1104 prefix *survey = pfx;
1105 int i;
1106 for (i = depth + 1; i; i--) {
1107 survey = survey->up;
1108 SVX_ASSERT(survey);
1110 s = osstrdup(sprint_prefix(survey));
1111 p = sprint_prefix(pfx);
1112 if (survey->filename) {
1113 /* TRANSLATORS: A station must be exported out of each level it is in, so
1114 * this would give "Station “\outer.inner.1” not exported from survey
1115 * “\outer”)":
1117 * *equate entrance outer.inner.1
1118 * *begin outer
1119 * *begin inner
1120 * *export 1
1121 * 1 2 1.23 045 -6
1122 * *end inner
1123 * *end outer
1125 * Here "survey" is a "cave map" rather than list of questions - it should be
1126 * translated to the terminology that cavers using the language would use.
1128 compile_diagnostic_pfx(DIAG_ERR, survey,
1129 /*Station “%s” not exported from survey “%s”*/26, p, s);
1130 } else {
1131 compile_diagnostic(DIAG_ERR, /*Station “%s” not exported from survey “%s”*/26, p, s);
1133 osfree(s);
1136 static void
1137 cmd_export(void)
1139 prefix *pfx;
1141 fExportUsed = fTrue;
1142 do {
1143 int depth = 0;
1144 pfx = read_prefix(PFX_STATION|PFX_NEW);
1145 if (pfx == NULL) {
1146 /* The argument was an existing station. */
1147 /* FIXME */
1148 } else {
1149 prefix *p = pfx;
1150 while (p != NULL && p != pcs->Prefix) {
1151 depth++;
1152 p = p->up;
1154 /* Something like: *export \foo, but we've excluded use of root */
1155 SVX_ASSERT(p);
1157 /* *export \ or similar bogus stuff */
1158 SVX_ASSERT(depth);
1159 #if 0
1160 printf("C min %d max %d depth %d pfx %s\n",
1161 pfx->min_export, pfx->max_export, depth, sprint_prefix(pfx));
1162 #endif
1163 if (pfx->min_export == 0) {
1164 /* not encountered *export for this name before */
1165 if (pfx->max_export > depth) report_missing_export(pfx, depth);
1166 pfx->min_export = pfx->max_export = depth;
1167 } else if (pfx->min_export != USHRT_MAX) {
1168 /* FIXME: what to do if a station is marked for inferred exports
1169 * but is then explicitly exported? Currently we just ignore the
1170 * explicit export... */
1171 if (pfx->min_export - 1 > depth) {
1172 report_missing_export(pfx, depth);
1173 } else if (pfx->min_export - 1 < depth) {
1174 /* TRANSLATORS: Here "station" is a survey station, not a train station.
1176 * Exporting a station twice gives this error:
1178 * *begin example
1179 * *export 1
1180 * *export 1
1181 * 1 2 1.24 045 -6
1182 * *end example */
1183 compile_diagnostic(DIAG_ERR, /*Station “%s” already exported*/66,
1184 sprint_prefix(pfx));
1186 pfx->min_export = depth;
1188 skipblanks();
1189 } while (!isEol(ch) && !isComm(ch));
1192 static void
1193 cmd_data(void)
1195 static const sztok dtab[] = {
1196 {"ALTITUDE", Dz },
1197 {"BACKBEARING", BackComp },
1198 {"BACKCLINO", BackClino }, /* alternative name */
1199 {"BACKCOMPASS", BackComp }, /* alternative name */
1200 {"BACKGRADIENT", BackClino },
1201 {"BACKLENGTH", BackTape },
1202 {"BACKTAPE", BackTape }, /* alternative name */
1203 {"BEARING", Comp },
1204 {"CEILING", Up }, /* alternative name */
1205 {"CLINO", Clino }, /* alternative name */
1206 {"COMPASS", Comp }, /* alternative name */
1207 {"COUNT", Count }, /* FrCount&ToCount in multiline */
1208 {"DEPTH", Depth }, /* FrDepth&ToDepth in multiline */
1209 {"DEPTHCHANGE", DepthChange },
1210 {"DIRECTION", Dir },
1211 {"DOWN", Down },
1212 {"DX", Dx },
1213 {"DY", Dy },
1214 {"DZ", Dz },
1215 {"EASTING", Dx },
1216 {"FLOOR", Down }, /* alternative name */
1217 {"FROM", Fr },
1218 {"FROMCOUNT", FrCount },
1219 {"FROMDEPTH", FrDepth },
1220 {"GRADIENT", Clino },
1221 {"IGNORE", Ignore },
1222 {"IGNOREALL", IgnoreAll },
1223 {"LEFT", Left },
1224 {"LENGTH", Tape },
1225 {"NEWLINE", Newline },
1226 {"NORTHING", Dy },
1227 {"RIGHT", Right },
1228 {"STATION", Station }, /* Fr&To in multiline */
1229 {"TAPE", Tape }, /* alternative name */
1230 {"TO", To },
1231 {"TOCOUNT", ToCount },
1232 {"TODEPTH", ToDepth },
1233 {"UP", Up },
1234 {NULL, End }
1237 #define MASK_stns BIT(Fr) | BIT(To) | BIT(Station)
1238 #define MASK_tape BIT(Tape) | BIT(BackTape) | BIT(FrCount) | BIT(ToCount) | BIT(Count)
1239 #define MASK_dpth BIT(FrDepth) | BIT(ToDepth) | BIT(Depth) | BIT(DepthChange)
1240 #define MASK_comp BIT(Comp) | BIT(BackComp)
1241 #define MASK_clin BIT(Clino) | BIT(BackClino)
1243 #define MASK_NORMAL MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_clin
1244 #define MASK_DIVING MASK_NORMAL | MASK_dpth
1245 #define MASK_CARTESIAN MASK_stns | BIT(Dx) | BIT(Dy) | BIT(Dz)
1246 #define MASK_CYLPOLAR MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_dpth
1247 #define MASK_NOSURVEY MASK_stns
1248 #define MASK_PASSAGE BIT(Station) | BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down)
1250 /* readings which may be given for each style */
1251 static const unsigned long mask[] = {
1252 MASK_NORMAL, MASK_DIVING, MASK_CARTESIAN, MASK_CYLPOLAR, MASK_NOSURVEY,
1253 MASK_PASSAGE
1256 /* readings which may be omitted for each style */
1257 static const unsigned long mask_optional[] = {
1258 BIT(Dir) | BIT(Clino) | BIT(BackClino),
1259 BIT(Dir) | BIT(Clino) | BIT(BackClino),
1261 BIT(Dir),
1263 0 /* BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down), */
1266 /* all valid readings */
1267 static const unsigned long mask_all[] = {
1268 MASK_NORMAL | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1269 MASK_DIVING | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1270 MASK_CARTESIAN | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1271 MASK_CYLPOLAR | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1272 MASK_NOSURVEY | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1273 MASK_PASSAGE | BIT(Ignore) | BIT(IgnoreAll) | BIT(End)
1275 #define STYLE_DEFAULT -2
1276 #define STYLE_UNKNOWN -1
1278 static const sztok styletab[] = {
1279 {"CARTESIAN", STYLE_CARTESIAN },
1280 {"CYLPOLAR", STYLE_CYLPOLAR },
1281 {"DEFAULT", STYLE_DEFAULT },
1282 {"DIVING", STYLE_DIVING },
1283 {"NORMAL", STYLE_NORMAL },
1284 {"NOSURVEY", STYLE_NOSURVEY },
1285 {"PASSAGE", STYLE_PASSAGE },
1286 {"TOPOFIL", STYLE_NORMAL },
1287 {NULL, STYLE_UNKNOWN }
1290 #define m_multi (BIT(Station) | BIT(Count) | BIT(Depth))
1292 int style, k = 0;
1293 reading d;
1294 unsigned long mUsed = 0;
1295 int old_style = pcs->style;
1297 /* after a bad *data command ignore survey data until the next
1298 * *data command to avoid an avalanche of errors */
1299 pcs->style = STYLE_IGNORE;
1301 get_token();
1302 style = match_tok(styletab, TABSIZE(styletab));
1304 if (style == STYLE_DEFAULT) {
1305 default_style(pcs);
1306 return;
1309 if (style == STYLE_UNKNOWN) {
1310 if (!buffer[0]) {
1311 /* "*data" reinitialises the current style - for *data passage that
1312 * breaks the passage.
1314 pcs->style = style = old_style;
1315 goto reinit_style;
1317 /* TRANSLATORS: e.g. trying to refer to an invalid FNORD data style */
1318 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Data style “%s” unknown*/65, buffer);
1319 return;
1322 skipblanks();
1323 #ifndef NO_DEPRECATED
1324 /* Olde syntax had optional field for survey grade, so allow an omit
1325 * but issue a warning about it */
1326 if (isOmit(ch)) {
1327 static int data_depr_count = 0;
1328 if (data_depr_count < 5) {
1329 compile_diagnostic(DIAG_WARN|DIAG_BUF, /*“*data %s %c …” is deprecated - use “*data %s …” instead*/104,
1330 buffer, ch, buffer);
1331 if (++data_depr_count == 5)
1332 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
1334 nextch();
1336 #endif
1338 int kMac = 6; /* minimum for NORMAL style */
1339 reading *new_order = osmalloc(kMac * sizeof(reading));
1340 char *style_name = osstrdup(buffer);
1341 do {
1342 filepos fp;
1343 get_pos(&fp);
1344 get_token();
1345 d = match_tok(dtab, TABSIZE(dtab));
1346 /* only token allowed after IGNOREALL is NEWLINE */
1347 if (k && new_order[k - 1] == IgnoreAll && d != Newline) {
1348 set_pos(&fp);
1349 break;
1351 /* Note: an unknown token is reported as trailing garbage */
1352 if (!TSTBIT(mask_all[style], d)) {
1353 /* TRANSLATORS: a data "style" is something like NORMAL, DIVING, etc.
1354 * a "reading" is one of FROM, TO, TAPE, COMPASS, CLINO for NORMAL
1355 * neither style nor reading is a keyword in the program This error
1356 * complains about a depth gauge reading in normal style, for example
1358 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP,
1359 /*Reading “%s” not allowed in data style “%s”*/63,
1360 buffer, style_name);
1361 osfree(style_name);
1362 osfree(new_order);
1363 return;
1365 if (TSTBIT(mUsed, Newline) && TSTBIT(m_multi, d)) {
1366 /* TRANSLATORS: caused by e.g.
1368 * *data diving station newline depth tape compass
1370 * ("depth" needs to occur before "newline"). */
1371 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP,
1372 /*Reading “%s” must occur before NEWLINE*/225, buffer);
1373 osfree(style_name);
1374 osfree(new_order);
1375 return;
1377 /* Check for duplicates unless it's a special reading:
1378 * IGNOREALL,IGNORE (duplicates allowed) ; END (not possible)
1380 if (!((BIT(Ignore) | BIT(End) | BIT(IgnoreAll)) & BIT(d))) {
1381 if (TSTBIT(mUsed, d)) {
1382 /* TRANSLATORS: complains about a situation like trying to define
1383 * two from stations per leg */
1384 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Duplicate reading “%s”*/67, buffer);
1385 osfree(style_name);
1386 osfree(new_order);
1387 return;
1388 } else {
1389 /* Check for previously listed readings which are incompatible
1390 * with this one - e.g. Count vs FrCount */
1391 bool fBad = fFalse;
1392 switch (d) {
1393 case Station:
1394 if (mUsed & (BIT(Fr) | BIT(To))) fBad = fTrue;
1395 break;
1396 case Fr: case To:
1397 if (TSTBIT(mUsed, Station)) fBad = fTrue;
1398 break;
1399 case Count:
1400 if (mUsed & (BIT(FrCount) | BIT(ToCount) | BIT(Tape)))
1401 fBad = fTrue;
1402 break;
1403 case FrCount: case ToCount:
1404 if (mUsed & (BIT(Count) | BIT(Tape)))
1405 fBad = fTrue;
1406 break;
1407 case Depth:
1408 if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(DepthChange)))
1409 fBad = fTrue;
1410 break;
1411 case FrDepth: case ToDepth:
1412 if (mUsed & (BIT(Depth) | BIT(DepthChange))) fBad = fTrue;
1413 break;
1414 case DepthChange:
1415 if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(Depth)))
1416 fBad = fTrue;
1417 break;
1418 case Newline:
1419 if (mUsed & ~m_multi) {
1420 /* TRANSLATORS: e.g.
1422 * *data normal from to tape newline compass clino */
1423 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*NEWLINE can only be preceded by STATION, DEPTH, and COUNT*/226);
1424 osfree(style_name);
1425 osfree(new_order);
1426 return;
1428 if (k == 0) {
1429 /* TRANSLATORS: error from:
1431 * *data normal newline from to tape compass clino */
1432 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*NEWLINE can’t be the first reading*/222);
1433 osfree(style_name);
1434 osfree(new_order);
1435 return;
1437 break;
1438 default: /* avoid compiler warnings about unhandled enums */
1439 break;
1441 if (fBad) {
1442 /* Not entirely happy with phrasing this... */
1443 /* TRANSLATORS: This is an error from the *DATA command. It
1444 * means that a reading (which will appear where %s is isn't
1445 * valid as the list of readings has already included the same
1446 * reading, or an equivalent one (e.g. you can't have both
1447 * DEPTH and DEPTHCHANGE together). */
1448 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Reading “%s” duplicates previous reading(s)*/77,
1449 buffer);
1450 osfree(style_name);
1451 osfree(new_order);
1452 return;
1454 mUsed |= BIT(d); /* used to catch duplicates */
1457 if (k && new_order[k - 1] == IgnoreAll) {
1458 SVX_ASSERT(d == Newline);
1459 k--;
1460 d = IgnoreAllAndNewLine;
1462 if (k >= kMac) {
1463 kMac = kMac * 2;
1464 new_order = osrealloc(new_order, kMac * sizeof(reading));
1466 new_order[k++] = d;
1467 } while (d != End);
1469 if (k >= 2 && new_order[k - 2] == Newline) {
1470 /* TRANSLATORS: error from:
1472 * *data normal from to tape compass clino newline */
1473 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*NEWLINE can’t be the last reading*/223);
1474 osfree(style_name);
1475 osfree(new_order);
1476 return;
1479 if (style == STYLE_NOSURVEY) {
1480 if (TSTBIT(mUsed, Station)) {
1481 if (k >= kMac) {
1482 kMac = kMac * 2;
1483 new_order = osrealloc(new_order, kMac * sizeof(reading));
1485 new_order[k - 1] = Newline;
1486 new_order[k++] = End;
1488 } else if (style == STYLE_PASSAGE) {
1489 /* Station doesn't mean "multiline" for STYLE_PASSAGE. */
1490 } else if (!TSTBIT(mUsed, Newline) && (m_multi & mUsed)) {
1491 /* TRANSLATORS: Error given by something like:
1493 * *data normal station tape compass clino
1495 * ("station" signifies interleaved data). */
1496 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Interleaved readings, but no NEWLINE*/224);
1497 osfree(style_name);
1498 osfree(new_order);
1499 return;
1502 #if 0
1503 printf("mUsed = 0x%x\n", mUsed);
1504 #endif
1506 /* Check the supplied readings form a sufficient set. */
1507 if (style != STYLE_PASSAGE) {
1508 if ((mUsed & (BIT(Fr) | BIT(To))) == (BIT(Fr) | BIT(To)))
1509 mUsed |= BIT(Station);
1510 else if (TSTBIT(mUsed, Station))
1511 mUsed |= BIT(Fr) | BIT(To);
1514 if (mUsed & (BIT(Comp) | BIT(BackComp)))
1515 mUsed |= BIT(Comp) | BIT(BackComp);
1517 if (mUsed & (BIT(Clino) | BIT(BackClino)))
1518 mUsed |= BIT(Clino) | BIT(BackClino);
1520 if ((mUsed & (BIT(FrDepth) | BIT(ToDepth))) == (BIT(FrDepth) | BIT(ToDepth)))
1521 mUsed |= BIT(Depth) | BIT(DepthChange);
1522 else if (mUsed & (BIT(Depth) | BIT(DepthChange)))
1523 mUsed |= BIT(FrDepth) | BIT(ToDepth) | BIT(Depth) | BIT(DepthChange);
1525 if ((mUsed & (BIT(FrCount) | BIT(ToCount))) == (BIT(FrCount) | BIT(ToCount)))
1526 mUsed |= BIT(Count) | BIT(Tape) | BIT(BackTape);
1527 else if (mUsed & (BIT(Count) | BIT(Tape) | BIT(BackTape)))
1528 mUsed |= BIT(FrCount) | BIT(ToCount) | BIT(Count) | BIT(Tape) | BIT(BackTape);
1530 #if 0
1531 printf("mUsed = 0x%x, opt = 0x%x, mask = 0x%x\n", mUsed,
1532 mask_optional[style], mask[style]);
1533 #endif
1535 if (((mUsed &~ BIT(Newline)) | mask_optional[style]) != mask[style]) {
1536 /* Test should only fail with too few bits set, not too many */
1537 SVX_ASSERT((((mUsed &~ BIT(Newline)) | mask_optional[style])
1538 &~ mask[style]) == 0);
1539 /* TRANSLATORS: i.e. not enough readings for the style. */
1540 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Too few readings for data style “%s”*/64, style_name);
1541 osfree(style_name);
1542 osfree(new_order);
1543 return;
1546 /* don't free default ordering or ordering used by parent */
1547 if (pcs->ordering != default_order &&
1548 !(pcs->next && pcs->next->ordering == pcs->ordering))
1549 osfree((reading*)pcs->ordering);
1551 pcs->style = style;
1552 pcs->ordering = new_order;
1554 osfree(style_name);
1556 reinit_style:
1557 if (style == STYLE_PASSAGE) {
1558 lrudlist * new_psg = osnew(lrudlist);
1559 new_psg->tube = NULL;
1560 new_psg->next = model;
1561 model = new_psg;
1562 next_lrud = &(new_psg->tube);
1566 static void
1567 cmd_units(void)
1569 int units, quantity;
1570 unsigned long qmask;
1571 unsigned long m; /* mask with bit x set to indicate quantity x specified */
1572 real factor;
1573 filepos fp;
1575 qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1577 if (!qmask) return;
1578 if (qmask == BIT(Q_DEFAULT)) {
1579 default_units(pcs);
1580 return;
1583 get_pos(&fp);
1584 factor = read_numeric(fTrue);
1585 if (factor == 0.0) {
1586 set_pos(&fp);
1587 /* TRANSLATORS: error message given by "*units tape 0 feet" - it’s
1588 * meaningless to say your tape is marked in "0 feet" (but you might
1589 * measure distance by counting knots on a diving line, and tie them
1590 * every "2 feet"). */
1591 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /**UNITS factor must be non-zero*/200);
1592 skipline();
1593 return;
1596 units = get_units(qmask, fTrue);
1597 if (units == UNITS_NULL) return;
1598 if (TSTBIT(qmask, Q_GRADIENT))
1599 pcs->f_clino_percent = (units == UNITS_PERCENT);
1600 if (TSTBIT(qmask, Q_BACKGRADIENT))
1601 pcs->f_backclino_percent = (units == UNITS_PERCENT);
1603 if (TSTBIT(qmask, Q_BEARING)) {
1604 pcs->f_bearing_quadrants = (units == UNITS_QUADRANTS);
1606 if (TSTBIT(qmask, Q_BACKBEARING)) {
1607 pcs->f_backbearing_quadrants = (units == UNITS_QUADRANTS);
1610 if (factor == HUGE_REAL) {
1611 factor = factor_tab[units];
1612 } else {
1613 factor *= factor_tab[units];
1616 for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1617 if (qmask & m) pcs->units[quantity] = factor;
1620 static void
1621 cmd_calibrate(void)
1623 real sc, z;
1624 unsigned long qmask, m;
1625 int quantity;
1626 filepos fp;
1628 qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1629 if (!qmask) return; /* error already reported */
1631 if (qmask == BIT(Q_DEFAULT)) {
1632 default_calib(pcs);
1633 return;
1636 if (((qmask & LEN_QMASK)) && ((qmask & ANG_QMASK))) {
1637 /* TRANSLATORS: e.g.
1639 * *calibrate tape compass 1 1
1641 compile_diagnostic(DIAG_ERR|DIAG_SKIP, /*Can’t calibrate angular and length quantities together*/227);
1642 return;
1645 z = read_numeric(fFalse);
1646 get_pos(&fp);
1647 sc = read_numeric(fTrue);
1648 if (sc == HUGE_REAL) {
1649 if (isalpha(ch)) {
1650 int units = get_units(qmask, fFalse);
1651 if (units == UNITS_NULL) {
1652 return;
1654 z *= factor_tab[units];
1655 sc = read_numeric(fTrue);
1656 if (sc == HUGE_REAL) {
1657 sc = (real)1.0;
1658 } else {
1659 /* Adjustment applied is: (reading - z) * sc
1660 * We want: reading * sc - z
1661 * So divide z by sc so the applied adjustment does what we want.
1663 z /= sc;
1665 } else {
1666 sc = (real)1.0;
1670 if (sc == HUGE_REAL) sc = (real)1.0;
1671 /* check for declination scale */
1672 if (TSTBIT(qmask, Q_DECLINATION) && sc != 1.0) {
1673 set_pos(&fp);
1674 /* TRANSLATORS: DECLINATION is a built-in keyword, so best not to
1675 * translate */
1676 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Scale factor must be 1.0 for DECLINATION*/40);
1677 skipline();
1678 return;
1680 if (sc == 0.0) {
1681 set_pos(&fp);
1682 /* TRANSLATORS: If the scale factor for an instrument is zero, then any
1683 * reading would be mapped to zero, which doesn't make sense. */
1684 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Scale factor must be non-zero*/391);
1685 skipline();
1686 return;
1688 for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1) {
1689 if (qmask & m) {
1690 pcs->z[quantity] = pcs->units[quantity] * z;
1691 pcs->sc[quantity] = sc;
1696 static void
1697 cmd_declination(void)
1699 real v = read_numeric(fTrue);
1700 if (v == HUGE_REAL) {
1701 get_token_no_blanks();
1702 if (strcmp(ucbuffer, "AUTO") != 0) {
1703 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_COL, /*Expected number or “AUTO”*/309);
1704 return;
1706 /* *declination auto X Y Z */
1707 real x = read_numeric(fFalse);
1708 real y = read_numeric(fFalse);
1709 real z = read_numeric(fFalse);
1710 if (!pcs->proj_str) {
1711 compile_diagnostic(DIAG_ERR, /*Input coordinate system must be specified for “*DECLINATION AUTO”*/301);
1712 return;
1714 /* Convert to WGS84 lat long. */
1715 PJ *transform = proj_create_crs_to_crs(PJ_DEFAULT_CTX,
1716 pcs->proj_str,
1717 WGS84_DATUM_STRING,
1718 NULL);
1719 if (transform) {
1720 // Normalise the output order so x is longitude and y latitude - by
1721 // default new PROJ has them switched for EPSG:4326 which just seems
1722 // confusing.
1723 PJ* pj_norm = proj_normalize_for_visualization(PJ_DEFAULT_CTX,
1724 transform);
1725 proj_destroy(transform);
1726 transform = pj_norm;
1729 if (proj_angular_input(transform, PJ_FWD)) {
1730 /* Input coordinate system expects radians. */
1731 x = rad(x);
1732 y = rad(y);
1735 PJ_COORD coord = {{x, y, z, HUGE_VAL}};
1736 coord = proj_trans(transform, PJ_FWD, coord);
1737 x = coord.xyzt.x;
1738 y = coord.xyzt.y;
1739 z = coord.xyzt.z;
1741 if (x == HUGE_VAL || y == HUGE_VAL || z == HUGE_VAL) {
1742 compile_diagnostic(DIAG_ERR, /*Failed to convert coordinates: %s*/436,
1743 proj_errno_string(proj_errno(transform)));
1744 // Set dummy values which are finite.
1745 x = y = z = 0;
1747 proj_destroy(transform);
1748 double lon = rad(x);
1749 double lat = rad(y);
1750 pcs->z[Q_DECLINATION] = HUGE_REAL;
1751 pcs->dec_lat = lat;
1752 pcs->dec_lon = lon;
1753 pcs->dec_alt = z;
1754 /* Invalidate cached declination. */
1755 pcs->declination = HUGE_REAL;
1757 PJ *pj = proj_create(PJ_DEFAULT_CTX, proj_str_out);
1758 PJ_COORD lp;
1759 lp.lp.lam = lon;
1760 lp.lp.phi = lat;
1761 #if PROJ_VERSION_MAJOR < 8 || \
1762 (PROJ_VERSION_MAJOR == 8 && PROJ_VERSION_MINOR < 2)
1763 // Code adapted from fix in PROJ 8.2.0 to make proj_factors() work in
1764 // cases we need (e.g. a CRS specified as "EPSG:<number>").
1765 switch (proj_get_type(pj)) {
1766 case PJ_TYPE_PROJECTED_CRS: {
1767 // If it is a projected CRS, then compute the factors on the conversion
1768 // associated to it. We need to start from a temporary geographic CRS
1769 // using the same datum as the one of the projected CRS, and with
1770 // input coordinates being in longitude, latitude order in radian,
1771 // to be consistent with the expectations of the lp input parameter.
1773 PJ * geodetic_crs = proj_get_source_crs(PJ_DEFAULT_CTX, pj);
1774 if (!geodetic_crs)
1775 break;
1776 PJ * datum = proj_crs_get_datum(PJ_DEFAULT_CTX, geodetic_crs);
1777 PJ * datum_ensemble = proj_crs_get_datum_ensemble(PJ_DEFAULT_CTX, geodetic_crs);
1778 PJ * cs = proj_create_ellipsoidal_2D_cs(
1779 PJ_DEFAULT_CTX, PJ_ELLPS2D_LONGITUDE_LATITUDE, "Radian", 1.0);
1780 PJ * temp = proj_create_geographic_crs_from_datum(
1781 PJ_DEFAULT_CTX, "unnamed crs", datum ? datum : datum_ensemble,
1782 cs);
1783 proj_destroy(datum);
1784 proj_destroy(datum_ensemble);
1785 proj_destroy(cs);
1786 proj_destroy(geodetic_crs);
1787 PJ * newOp = proj_create_crs_to_crs_from_pj(PJ_DEFAULT_CTX, temp, pj, NULL, NULL);
1788 proj_destroy(temp);
1789 if (!newOp) {
1790 break;
1792 proj_destroy(pj);
1793 pj = newOp;
1794 break;
1796 default:
1797 break;
1799 #endif
1800 PJ_FACTORS factors = proj_factors(pj, lp);
1801 pcs->convergence = factors.meridian_convergence;
1802 proj_destroy(pj);
1804 } else {
1805 /* *declination D UNITS */
1806 int units = get_units(BIT(Q_DECLINATION), fFalse);
1807 if (units == UNITS_NULL) {
1808 return;
1810 pcs->z[Q_DECLINATION] = -v * factor_tab[units];
1811 pcs->convergence = 0;
1815 #ifndef NO_DEPRECATED
1816 static void
1817 cmd_default(void)
1819 static const sztok defaulttab[] = {
1820 { "CALIBRATE", CMD_CALIBRATE },
1821 { "DATA", CMD_DATA },
1822 { "UNITS", CMD_UNITS },
1823 { NULL, CMD_NULL }
1825 static int default_depr_count = 0;
1827 if (default_depr_count < 5) {
1828 /* TRANSLATORS: If you're unsure what "deprecated" means, see:
1829 * https://en.wikipedia.org/wiki/Deprecation */
1830 compile_diagnostic(DIAG_WARN|DIAG_COL, /**DEFAULT is deprecated - use *CALIBRATE/DATA/SD/UNITS with argument DEFAULT instead*/20);
1831 if (++default_depr_count == 5)
1832 compile_diagnostic(DIAG_WARN, /*Further uses of this deprecated feature will not be reported*/95);
1835 get_token();
1836 switch (match_tok(defaulttab, TABSIZE(defaulttab))) {
1837 case CMD_CALIBRATE:
1838 default_calib(pcs);
1839 break;
1840 case CMD_DATA:
1841 default_style(pcs);
1842 default_grade(pcs);
1843 break;
1844 case CMD_UNITS:
1845 default_units(pcs);
1846 break;
1847 default:
1848 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown setting “%s”*/41, buffer);
1851 #endif
1853 static void
1854 cmd_include(void)
1856 char *pth, *fnm = NULL;
1857 int fnm_len;
1858 #ifndef NO_DEPRECATED
1859 prefix *root_store;
1860 #endif
1861 int ch_store;
1863 pth = path_from_fnm(file.filename);
1865 read_string(&fnm, &fnm_len);
1867 #ifndef NO_DEPRECATED
1868 /* Since *begin / *end nesting cannot cross file boundaries we only
1869 * need to preserve the prefix if the deprecated *prefix command
1870 * can be used */
1871 root_store = root;
1872 root = pcs->Prefix; /* Root for include file is current prefix */
1873 #endif
1874 ch_store = ch;
1876 data_file(pth, fnm);
1878 #ifndef NO_DEPRECATED
1879 root = root_store; /* and restore root */
1880 #endif
1881 ch = ch_store;
1883 s_free(&fnm);
1884 osfree(pth);
1887 static void
1888 cmd_sd(void)
1890 real sd, variance;
1891 int units;
1892 unsigned long qmask, m;
1893 int quantity;
1894 qmask = get_qlist(BIT(Q_DECLINATION));
1895 if (!qmask) return; /* no quantities found - error already reported */
1897 if (qmask == BIT(Q_DEFAULT)) {
1898 default_grade(pcs);
1899 return;
1901 sd = read_numeric(fFalse);
1902 if (sd <= (real)0.0) {
1903 compile_diagnostic(DIAG_ERR|DIAG_SKIP|DIAG_COL, /*Standard deviation must be positive*/48);
1904 return;
1906 units = get_units(qmask, fFalse);
1907 if (units == UNITS_NULL) return;
1909 sd *= factor_tab[units];
1910 variance = sqrd(sd);
1912 for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1913 if (qmask & m) pcs->Var[quantity] = variance;
1916 static void
1917 cmd_title(void)
1919 if (!fExplicitTitle && pcs->Prefix == root) {
1920 /* If we don't have an explicit title yet, and we're currently in the
1921 * root prefix, use this title explicitly. */
1922 fExplicitTitle = fTrue;
1923 read_string(&survey_title, &survey_title_len);
1924 } else {
1925 /* parse and throw away this title (but still check rest of line) */
1926 char *s = NULL;
1927 int len;
1928 read_string(&s, &len);
1929 s_free(&s);
1933 static const sztok case_tab[] = {
1934 {"PRESERVE", OFF},
1935 {"TOLOWER", LOWER},
1936 {"TOUPPER", UPPER},
1937 {NULL, -1}
1940 static void
1941 cmd_case(void)
1943 int setting;
1944 get_token();
1945 setting = match_tok(case_tab, TABSIZE(case_tab));
1946 if (setting != -1) {
1947 pcs->Case = setting;
1948 } else {
1949 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Found “%s”, expecting “PRESERVE”, “TOUPPER”, or “TOLOWER”*/10, buffer);
1953 typedef enum {
1954 CS_NONE = -1,
1955 CS_CUSTOM,
1956 CS_EPSG,
1957 CS_ESRI,
1958 CS_EUR,
1959 CS_IJTSK,
1960 CS_JTSK,
1961 CS_LAT,
1962 CS_LOCAL,
1963 CS_LONG,
1964 CS_OSGB,
1965 CS_S_MERC,
1966 CS_UTM
1967 } cs_class;
1969 static const sztok cs_tab[] = {
1970 {"CUSTOM", CS_CUSTOM},
1971 {"EPSG", CS_EPSG}, /* EPSG:<number> */
1972 {"ESRI", CS_ESRI}, /* ESRI:<number> */
1973 {"EUR", CS_EUR}, /* EUR79Z30 */
1974 {"IJTSK", CS_IJTSK}, /* IJTSK or IJTSK03 */
1975 {"JTSK", CS_JTSK}, /* JTSK or JTSK03 */
1976 {"LAT", CS_LAT}, /* LAT-LONG */
1977 {"LOCAL", CS_LOCAL},
1978 {"LONG", CS_LONG}, /* LONG-LAT */
1979 {"OSGB", CS_OSGB}, /* OSGB:<H, N, O, S or T><A-Z except I> */
1980 {"S", CS_S_MERC}, /* S-MERC */
1981 {"UTM", CS_UTM}, /* UTM<zone><N or S or nothing> */
1982 {NULL, CS_NONE}
1985 static void
1986 cmd_cs(void)
1988 char * proj_str = NULL;
1989 int proj_str_len;
1990 cs_class cs;
1991 int cs_sub = INT_MIN;
1992 filepos fp;
1993 bool output = fFalse;
1994 enum { YES, NO, MAYBE } ok_for_output = YES;
1995 static bool had_cs = fFalse;
1997 if (!had_cs) {
1998 had_cs = fTrue;
1999 if (first_fix_name) {
2000 compile_diagnostic_at(DIAG_ERR,
2001 first_fix_filename, first_fix_line,
2002 /*Station “%s” fixed before CS command first used*/442,
2003 sprint_prefix(first_fix_name));
2007 get_pos(&fp);
2008 /* Note get_token() only accepts letters - it'll stop at digits so "UTM12"
2009 * will give token "UTM". */
2010 get_token();
2011 if (strcmp(ucbuffer, "OUT") == 0) {
2012 output = fTrue;
2013 get_pos(&fp);
2014 get_token();
2016 cs = match_tok(cs_tab, TABSIZE(cs_tab));
2017 switch (cs) {
2018 case CS_NONE:
2019 break;
2020 case CS_CUSTOM:
2021 ok_for_output = MAYBE;
2022 get_pos(&fp);
2023 read_string(&proj_str, &proj_str_len);
2024 cs_sub = 0;
2025 break;
2026 case CS_EPSG: case CS_ESRI:
2027 ok_for_output = MAYBE;
2028 if (ch == ':' && isdigit(nextch())) {
2029 unsigned n = read_uint();
2030 if (n < 1000000) {
2031 cs_sub = (int)n;
2034 break;
2035 case CS_EUR:
2036 if (isdigit(ch) &&
2037 read_uint() == 79 &&
2038 (ch == 'Z' || ch == 'z') &&
2039 isdigit(nextch()) &&
2040 read_uint() == 30) {
2041 cs_sub = 7930;
2043 break;
2044 case CS_JTSK:
2045 ok_for_output = NO;
2046 /* FALLTHRU */
2047 case CS_IJTSK:
2048 if (ch == '0') {
2049 if (nextch() == '3') {
2050 nextch();
2051 cs_sub = 3;
2053 } else {
2054 cs_sub = 0;
2056 break;
2057 case CS_LAT: case CS_LONG:
2058 ok_for_output = NO;
2059 if (ch == '-') {
2060 nextch();
2061 get_token_no_blanks();
2062 cs_class cs2 = match_tok(cs_tab, TABSIZE(cs_tab));
2063 if ((cs ^ cs2) == (CS_LAT ^ CS_LONG)) {
2064 cs_sub = 0;
2067 break;
2068 case CS_LOCAL:
2069 cs_sub = 0;
2070 break;
2071 case CS_OSGB:
2072 if (ch == ':') {
2073 int uch1 = toupper(nextch());
2074 if (strchr("HNOST", uch1)) {
2075 int uch2 = toupper(nextch());
2076 if (uch2 >= 'A' && uch2 <= 'Z' && uch2 != 'I') {
2077 int x, y;
2078 nextch();
2079 if (uch1 > 'I') --uch1;
2080 uch1 -= 'A';
2081 if (uch2 > 'I') --uch2;
2082 uch2 -= 'A';
2083 x = uch1 % 5;
2084 y = uch1 / 5;
2085 x = (x * 5) + uch2 % 5;
2086 y = (y * 5) + uch2 / 5;
2087 cs_sub = y * 25 + x;
2091 break;
2092 case CS_S_MERC:
2093 if (ch == '-') {
2094 nextch();
2095 get_token_no_blanks();
2096 if (strcmp(ucbuffer, "MERC") == 0) {
2097 cs_sub = 0;
2100 break;
2101 case CS_UTM:
2102 if (isdigit(ch)) {
2103 unsigned n = read_uint();
2104 if (n >= 1 && n <= 60) {
2105 int uch = toupper(ch);
2106 cs_sub = (int)n;
2107 if (uch == 'S') {
2108 nextch();
2109 cs_sub = -cs_sub;
2110 } else if (uch == 'N') {
2111 nextch();
2115 break;
2117 if (cs_sub == INT_MIN || isalnum(ch)) {
2118 set_pos(&fp);
2119 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Unknown coordinate system*/434);
2120 skipline();
2121 return;
2123 /* Actually handle the cs */
2124 switch (cs) {
2125 case CS_NONE:
2126 break;
2127 case CS_CUSTOM:
2128 /* proj_str already set */
2129 break;
2130 case CS_EPSG:
2131 proj_str = osmalloc(32);
2132 sprintf(proj_str, "EPSG:%d", cs_sub);
2133 break;
2134 case CS_ESRI:
2135 proj_str = osmalloc(32);
2136 sprintf(proj_str, "ESRI:%d", cs_sub);
2137 break;
2138 case CS_EUR:
2139 proj_str = osstrdup("+proj=utm +zone=30 +ellps=intl +towgs84=-86,-98,-119,0,0,0,0 +no_defs");
2140 break;
2141 case CS_IJTSK:
2142 if (cs_sub == 0)
2143 proj_str = osstrdup("+proj=krovak +ellps=bessel +towgs84=570.8285,85.6769,462.842,4.9984,1.5867,5.2611,3.5623 +no_defs");
2144 else
2145 proj_str = osstrdup("+proj=krovak +ellps=bessel +towgs84=485.021,169.465,483.839,7.786342,4.397554,4.102655,0 +no_defs");
2146 break;
2147 case CS_JTSK:
2148 if (cs_sub == 0)
2149 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");
2150 else
2151 proj_str = osstrdup("+proj=krovak +czech +ellps=bessel +towgs84=485.021,169.465,483.839,7.786342,4.397554,4.102655,0 +no_defs");
2152 break;
2153 case CS_LAT:
2154 /* FIXME: Requires PROJ >= 4.8.0 for +axis, and the SDs will be
2155 * misapplied, so we may want to swap ourselves. Also, while
2156 * therion supports lat-long, I'm not totally convinced that it is
2157 * sensible to do so - people often say "lat-long", but probably
2158 * don't think that that's actually "Northing, Easting". This
2159 * seems like it'll result in people accidentally getting X and Y
2160 * swapped in their fixed points...
2162 #if 0
2163 proj_str = osstrdup("+proj=longlat +ellps=WGS84 +datum=WGS84 +axis=neu +no_defs");
2164 #endif
2165 break;
2166 case CS_LOCAL:
2167 /* FIXME: Is it useful to be able to explicitly specify this? */
2168 break;
2169 case CS_LONG:
2170 proj_str = osstrdup("EPSG:4326");
2171 break;
2172 case CS_OSGB: {
2173 int x = 14 - (cs_sub % 25);
2174 int y = (cs_sub / 25) - 20;
2175 proj_str = osmalloc(160);
2176 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);
2177 break;
2179 case CS_S_MERC:
2180 proj_str = osstrdup("EPSG:3857");
2181 break;
2182 case CS_UTM:
2183 proj_str = osmalloc(32);
2184 if (cs_sub > 0) {
2185 sprintf(proj_str, "EPSG:%d", 32600 + cs_sub);
2186 } else {
2187 sprintf(proj_str, "EPSG:%d", 32700 - cs_sub);
2189 break;
2192 if (!proj_str) {
2193 /* printf("CS %d:%d\n", (int)cs, cs_sub); */
2194 set_pos(&fp);
2195 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Unknown coordinate system*/434);
2196 skipline();
2197 return;
2200 if (output) {
2201 if (ok_for_output == NO) {
2202 set_pos(&fp);
2203 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Coordinate system unsuitable for output*/435);
2204 skipline();
2205 return;
2208 /* If the output projection is already set, we still need to create the
2209 * projection object for a custom projection, so we can report errors.
2210 * But if the string is identical, we know it's valid.
2212 if (!proj_str_out ||
2213 (ok_for_output == MAYBE && strcmp(proj_str, proj_str_out) != 0)) {
2214 PJ* pj = proj_create(PJ_DEFAULT_CTX, proj_str);
2215 if (!pj) {
2216 set_pos(&fp);
2217 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Invalid coordinate system: %s*/443,
2218 proj_errno_string(proj_context_errno(PJ_DEFAULT_CTX)));
2219 skipline();
2220 return;
2222 if (ok_for_output == MAYBE) {
2223 int type = proj_get_type(pj);
2224 if (type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
2225 type == PJ_TYPE_GEOGRAPHIC_3D_CRS) {
2226 set_pos(&fp);
2227 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Coordinate system unsuitable for output*/435);
2228 skipline();
2229 return;
2232 if (proj_str_out) {
2233 osfree(proj_str);
2234 } else {
2235 proj_str_out = proj_str;
2238 } else {
2239 if (proj_str_out && strcmp(proj_str, proj_str_out) == 0) {
2240 /* Same as the current output projection. */
2241 } else {
2242 PJ* pj = proj_create(PJ_DEFAULT_CTX, proj_str);
2243 if (!pj) {
2244 set_pos(&fp);
2245 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*Invalid coordinate system: %s*/443,
2246 proj_errno_string(proj_context_errno(PJ_DEFAULT_CTX)));
2247 skipline();
2248 return;
2250 proj_destroy(pj);
2253 /* Free proj if not used by parent, or as the output projection. */
2254 settings * p = pcs;
2255 if (p->proj_str && (!p->next || p->proj_str != p->next->proj_str))
2256 if (p->proj_str != proj_str_out)
2257 osfree(p->proj_str);
2258 p->proj_str = proj_str;
2262 static const sztok infer_tab[] = {
2263 { "EQUATES", INFER_EQUATES },
2264 { "EXPORTS", INFER_EXPORTS },
2265 { "PLUMBS", INFER_PLUMBS },
2266 #if 0 /* FIXME */
2267 { "SUBSURVEYS", INFER_SUBSURVEYS },
2268 #endif
2269 { NULL, INFER_NULL }
2272 static const sztok onoff_tab[] = {
2273 { "OFF", 0 },
2274 { "ON", 1 },
2275 { NULL, -1 }
2278 static void
2279 cmd_infer(void)
2281 infer_what setting;
2282 int on;
2283 get_token();
2284 setting = match_tok(infer_tab, TABSIZE(infer_tab));
2285 if (setting == INFER_NULL) {
2286 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Found “%s”, expecting “EQUATES”, “EXPORTS”, or “PLUMBS”*/31, buffer);
2287 return;
2289 get_token();
2290 on = match_tok(onoff_tab, TABSIZE(onoff_tab));
2291 if (on == -1) {
2292 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Found “%s”, expecting “ON” or “OFF”*/32, buffer);
2293 return;
2296 if (on) {
2297 pcs->infer |= BIT(setting);
2298 if (setting == INFER_EXPORTS) fExportUsed = fTrue;
2299 } else {
2300 pcs->infer &= ~BIT(setting);
2304 static void
2305 cmd_truncate(void)
2307 unsigned int truncate_at = 0; /* default is no truncation */
2308 filepos fp;
2310 get_pos(&fp);
2312 get_token();
2313 if (strcmp(ucbuffer, "OFF") != 0) {
2314 if (*ucbuffer) set_pos(&fp);
2315 truncate_at = read_uint();
2317 /* for backward compatibility, "*truncate 0" means "*truncate off" */
2318 pcs->Truncate = (truncate_at == 0) ? INT_MAX : truncate_at;
2321 static void
2322 cmd_ref(void)
2324 /* Just syntax check for now. */
2325 char *ref = NULL;
2326 int ref_len;
2327 read_string(&ref, &ref_len);
2328 s_free(&ref);
2331 static void
2332 cmd_require(void)
2334 const unsigned int version[] = {COMMAVERSION};
2335 const unsigned int *ver = version;
2336 filepos fp;
2338 skipblanks();
2339 get_pos(&fp);
2340 while (1) {
2341 int diff = *ver++ - read_uint();
2342 if (diff > 0) break;
2343 if (diff < 0) {
2344 size_t i, len;
2345 char *v;
2346 filepos fp_tmp;
2348 /* find end of version number */
2349 while (isdigit(ch) || ch == '.') nextch();
2350 get_pos(&fp_tmp);
2351 len = (size_t)(fp_tmp.offset - fp.offset);
2352 v = osmalloc(len + 1);
2353 set_pos(&fp);
2354 for (i = 0; i < len; i++) {
2355 v[i] = ch;
2356 nextch();
2358 v[i] = '\0';
2359 /* TRANSLATORS: Feel free to translate as "or newer" instead of "or
2360 * greater" if that gives a more natural translation. It's
2361 * technically not quite right when there are parallel active release
2362 * series (e.g. Survex 1.0.40 was released *after* 1.2.0), but this
2363 * seems unlikely to confuse users. "Survex" is the name of the
2364 * software, so should not be translated.
2366 * Here "survey" is a "cave map" rather than list of questions - it should be
2367 * translated to the terminology that cavers using the language would use.
2369 fatalerror_in_file(file.filename, file.line, /*Survex version %s or greater required to process this survey data.*/2, v);
2371 if (ch != '.') break;
2372 nextch();
2373 if (!isdigit(ch) || ver == version + sizeof(version) / sizeof(*version))
2374 break;
2376 /* skip rest of version number */
2377 while (isdigit(ch) || ch == '.') nextch();
2380 /* allocate new meta_data if need be */
2381 void
2382 copy_on_write_meta(settings *s)
2384 if (!s->meta || s->meta->ref_count != 0) {
2385 meta_data * meta_new = osnew(meta_data);
2386 if (!s->meta) {
2387 meta_new->days1 = meta_new->days2 = -1;
2388 } else {
2389 *meta_new = *(s->meta);
2391 meta_new->ref_count = 0;
2392 s->meta = meta_new;
2396 static void
2397 cmd_date(void)
2399 int year, month, day;
2400 int days1, days2;
2401 bool implicit_range = fFalse;
2402 filepos fp, fp2;
2404 get_pos(&fp);
2405 read_date(&year, &month, &day);
2406 days1 = days_since_1900(year, month ? month : 1, day ? day : 1);
2408 if (days1 > current_days_since_1900) {
2409 set_pos(&fp);
2410 compile_diagnostic(DIAG_WARN|DIAG_DATE, /*Date is in the future!*/80);
2413 skipblanks();
2414 if (ch == '-') {
2415 nextch();
2416 get_pos(&fp2);
2417 read_date(&year, &month, &day);
2418 } else {
2419 if (month && day) {
2420 days2 = days1;
2421 goto read;
2423 implicit_range = fTrue;
2426 if (month == 0) month = 12;
2427 if (day == 0) day = last_day(year, month);
2428 days2 = days_since_1900(year, month, day);
2430 if (!implicit_range && days2 > current_days_since_1900) {
2431 set_pos(&fp2);
2432 compile_diagnostic(DIAG_WARN|DIAG_DATE, /*Date is in the future!*/80);
2435 if (days2 < days1) {
2436 set_pos(&fp);
2437 compile_diagnostic(DIAG_ERR|DIAG_TOKEN, /*End of date range is before the start*/81);
2438 int tmp = days1;
2439 days1 = days2;
2440 days2 = tmp;
2443 read:
2444 if (!pcs->meta || pcs->meta->days1 != days1 || pcs->meta->days2 != days2) {
2445 copy_on_write_meta(pcs);
2446 pcs->meta->days1 = days1;
2447 pcs->meta->days2 = days2;
2448 /* Invalidate cached declination. */
2449 pcs->declination = HUGE_REAL;
2453 typedef void (*cmd_fn)(void);
2455 static const cmd_fn cmd_funcs[] = {
2456 cmd_alias,
2457 cmd_begin,
2458 cmd_calibrate,
2459 cmd_case,
2460 skipline, /*cmd_copyright,*/
2461 cmd_cs,
2462 cmd_data,
2463 cmd_date,
2464 cmd_declination,
2465 #ifndef NO_DEPRECATED
2466 cmd_default,
2467 #endif
2468 cmd_end,
2469 cmd_entrance,
2470 cmd_equate,
2471 cmd_export,
2472 cmd_fix,
2473 cmd_flags,
2474 cmd_include,
2475 cmd_infer,
2476 skipline, /*cmd_instrument,*/
2477 #ifndef NO_DEPRECATED
2478 cmd_prefix,
2479 #endif
2480 cmd_ref,
2481 cmd_require,
2482 cmd_sd,
2483 cmd_set,
2484 solve_network,
2485 skipline, /*cmd_team,*/
2486 cmd_title,
2487 cmd_truncate,
2488 cmd_units
2491 extern void
2492 handle_command(void)
2494 int cmdtok;
2495 get_token();
2496 cmdtok = match_tok(cmd_tab, TABSIZE(cmd_tab));
2498 if (cmdtok < 0 || cmdtok >= (int)(sizeof(cmd_funcs) / sizeof(cmd_fn))) {
2499 compile_diagnostic(DIAG_ERR|DIAG_BUF|DIAG_SKIP, /*Unknown command “%s”*/12, buffer);
2500 return;
2503 switch (cmdtok) {
2504 case CMD_EXPORT:
2505 if (!f_export_ok)
2506 /* TRANSLATORS: The *EXPORT command is only valid just after *BEGIN
2507 * <SURVEY>, so this would generate this error:
2509 * *begin fred
2510 * 1 2 1.23 045 -6
2511 * *export 2
2512 * *end fred */
2513 compile_diagnostic(DIAG_ERR, /**EXPORT must immediately follow “*BEGIN <SURVEY>”*/57);
2514 break;
2515 case CMD_ALIAS:
2516 case CMD_CALIBRATE:
2517 case CMD_CASE:
2518 case CMD_COPYRIGHT:
2519 case CMD_CS:
2520 case CMD_DATA:
2521 case CMD_DATE:
2522 case CMD_DECLINATION:
2523 case CMD_DEFAULT:
2524 case CMD_FLAGS:
2525 case CMD_INFER:
2526 case CMD_INSTRUMENT:
2527 case CMD_REF:
2528 case CMD_REQUIRE:
2529 case CMD_SD:
2530 case CMD_SET:
2531 case CMD_TEAM:
2532 case CMD_TITLE:
2533 case CMD_TRUNCATE:
2534 case CMD_UNITS:
2535 /* These can occur between *begin and *export */
2536 break;
2537 default:
2538 /* NB: additional handling for "*begin <survey>" in cmd_begin */
2539 f_export_ok = fFalse;
2540 break;
2543 cmd_funcs[cmdtok]();