source: git/src/commands.c @ 6eb50ab

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 6eb50ab was 6eb50ab, checked in by Olly Betts <olly@…>, 9 years ago

src/commands.c: Slightly simplify handling of the units scaling
factor.

  • Property mode set to 100644
File size: 58.9 KB
Line 
1/* commands.c
2 * Code for directives
3 * Copyright (C) 1991-2003,2004,2005,2006,2010,2011,2012,2013,2014,2015 Olly Betts
4 *
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.
9 *
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.
14 *
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
18 */
19
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24#include <assert.h>
25#include <limits.h>
26#include <stddef.h> /* for offsetof */
27
28#include <proj_api.h>
29
30#include "cavern.h"
31#include "commands.h"
32#include "datain.h"
33#include "date.h"
34#include "debug.h"
35#include "filename.h"
36#include "message.h"
37#include "netbits.h"
38#include "netskel.h"
39#include "out.h"
40#include "readval.h"
41#include "str.h"
42
43static void
44default_grade(settings *s)
45{
46   /* Values correspond to those in bcra5.svx */
47   s->Var[Q_POS] = (real)sqrd(0.05);
48   s->Var[Q_LENGTH] = (real)sqrd(0.05);
49   s->Var[Q_COUNT] = (real)sqrd(0.05);
50   s->Var[Q_DX] = s->Var[Q_DY] = s->Var[Q_DZ] = (real)sqrd(0.05);
51   s->Var[Q_BEARING] = (real)sqrd(rad(0.5));
52   s->Var[Q_GRADIENT] = (real)sqrd(rad(0.5));
53   s->Var[Q_BACKBEARING] = (real)sqrd(rad(0.5));
54   s->Var[Q_BACKGRADIENT] = (real)sqrd(rad(0.5));
55   /* SD of plumbed legs (0.25 degrees?) */
56   s->Var[Q_PLUMB] = (real)sqrd(rad(0.25));
57   /* SD of level legs (0.25 degrees?) */
58   s->Var[Q_LEVEL] = (real)sqrd(rad(0.25));
59   s->Var[Q_DEPTH] = (real)sqrd(0.05);
60}
61
62static void
63default_truncate(settings *s)
64{
65   s->Truncate = INT_MAX;
66}
67
68static void
69default_case(settings *s)
70{
71   s->Case = LOWER;
72}
73
74static reading default_order[] = { Fr, To, Tape, Comp, Clino, End };
75
76static void
77default_style(settings *s)
78{
79   s->style = STYLE_NORMAL;
80   s->ordering = default_order;
81   s->dash_for_anon_wall_station = fFalse;
82}
83
84static void
85default_prefix(settings *s)
86{
87   s->Prefix = root;
88}
89
90static void
91default_translate(settings *s)
92{
93   int i;
94   short *t;
95   if (s->next && s->next->Translate == s->Translate) {
96      t = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
97      memcpy(t - 1, s->Translate - 1, sizeof(short) * 257);
98      s->Translate = t;
99   }
100/*  SVX_ASSERT(EOF==-1);*/ /* important, since we rely on this */
101   t = s->Translate;
102   memset(t - 1, 0, sizeof(short) * 257);
103   for (i = '0'; i <= '9'; i++) t[i] = SPECIAL_NAMES;
104   for (i = 'A'; i <= 'Z'; i++) t[i] = SPECIAL_NAMES;
105   for (i = 'a'; i <= 'z'; i++) t[i] = SPECIAL_NAMES;
106
107   t['\t'] |= SPECIAL_BLANK;
108   t[' '] |= SPECIAL_BLANK;
109   t[','] |= SPECIAL_BLANK;
110   t[';'] |= SPECIAL_COMMENT;
111   t['\032'] |= SPECIAL_EOL; /* Ctrl-Z, so olde DOS text files are handled ok */
112   t[EOF] |= SPECIAL_EOL;
113   t['\n'] |= SPECIAL_EOL;
114   t['\r'] |= SPECIAL_EOL;
115   t['*'] |= SPECIAL_KEYWORD;
116   t['-'] |= SPECIAL_OMIT;
117   t['\\'] |= SPECIAL_ROOT;
118   t['.'] |= SPECIAL_SEPARATOR;
119   t['_'] |= SPECIAL_NAMES;
120   t['-'] |= SPECIAL_NAMES; /* Added in 0.97 prerelease 4 */
121   t['.'] |= SPECIAL_DECIMAL;
122   t['-'] |= SPECIAL_MINUS;
123   t['+'] |= SPECIAL_PLUS;
124#if 0 /* FIXME */
125   t['{'] |= SPECIAL_OPEN;
126   t['}'] |= SPECIAL_CLOSE;
127#endif
128}
129
130void
131default_units(settings *s)
132{
133   int quantity;
134   for (quantity = 0; quantity < Q_MAC; quantity++) {
135      if (TSTBIT(ANG_QMASK, quantity))
136         s->units[quantity] = (real)(M_PI / 180.0); /* degrees */
137      else
138         s->units[quantity] = (real)1.0; /* metres */
139   }
140   s->f_clino_percent = s->f_backclino_percent = fFalse;
141}
142
143void
144default_calib(settings *s)
145{
146   int quantity;
147   for (quantity = 0; quantity < Q_MAC; quantity++) {
148      s->z[quantity] = (real)0.0;
149      s->sc[quantity] = (real)1.0;
150   }
151}
152
153static void
154default_flags(settings *s)
155{
156   s->flags = 0;
157}
158
159extern void
160default_all(settings *s)
161{
162   default_truncate(s);
163   s->infer = 0;
164   default_case(s);
165   default_style(s);
166   default_prefix(s);
167   default_translate(s);
168   default_grade(s);
169   default_units(s);
170   default_calib(s);
171   default_flags(s);
172}
173
174char *buffer = NULL;
175static int buf_len;
176
177static char *ucbuffer = NULL;
178
179/* read token */
180extern void
181get_token(void)
182{
183   skipblanks();
184   get_token_no_blanks();
185}
186
187extern void
188get_token_no_blanks(void)
189{
190   int i = -1;
191
192   s_zero(&buffer);
193   osfree(ucbuffer);
194   while (isalpha(ch)) {
195      s_catchar(&buffer, &buf_len, (char)ch);
196      nextch();
197   }
198
199   if (!buffer) s_catchar(&buffer, &buf_len, '\0');
200
201   ucbuffer = osmalloc(buf_len);
202   do {
203      i++;
204      ucbuffer[i] = toupper(buffer[i]);
205   } while (buffer[i]);
206#if 0
207   printf("get_token_no_blanks() got “%s”\n", buffer);
208#endif
209}
210
211/* read word */
212static void
213get_word(void)
214{
215   s_zero(&buffer);
216   skipblanks();
217   while (!isBlank(ch) && !isEol(ch)) {
218      s_catchar(&buffer, &buf_len, (char)ch);
219      nextch();
220   }
221
222   if (!buffer) s_catchar(&buffer, &buf_len, '\0');
223#if 0
224   printf("get_word() got “%s”\n", buffer);
225#endif
226}
227
228/* match_tok() now uses binary chop
229 * tab argument should be alphabetically sorted (ascending)
230 */
231extern int
232match_tok(const sztok *tab, int tab_size)
233{
234   int a = 0, b = tab_size - 1, c;
235   int r;
236   assert(tab_size > 0); /* catch empty table */
237/*  printf("[%d,%d]",a,b); */
238   while (a <= b) {
239      c = (unsigned)(a + b) / 2;
240/*     printf(" %d",c); */
241      r = strcmp(tab[c].sz, ucbuffer);
242      if (r == 0) return tab[c].tok; /* match */
243      if (r < 0)
244         a = c + 1;
245      else
246         b = c - 1;
247   }
248   return tab[tab_size].tok; /* no match */
249}
250
251typedef enum {
252   CMD_NULL = -1, CMD_ALIAS, CMD_BEGIN, CMD_CALIBRATE, CMD_CASE, CMD_COPYRIGHT,
253   CMD_CS, CMD_DATA, CMD_DATE, CMD_DEFAULT, CMD_END, CMD_ENTRANCE, CMD_EQUATE,
254   CMD_EXPORT, CMD_FIX, CMD_FLAGS, CMD_INCLUDE, CMD_INFER, CMD_INSTRUMENT,
255   CMD_PREFIX, CMD_REQUIRE, CMD_SD, CMD_SET, CMD_SOLVE,
256   CMD_TEAM, CMD_TITLE, CMD_TRUNCATE, CMD_UNITS
257} cmds;
258
259static const sztok cmd_tab[] = {
260     {"ALIAS",     CMD_ALIAS},
261     {"BEGIN",     CMD_BEGIN},
262     {"CALIBRATE", CMD_CALIBRATE},
263     {"CASE",      CMD_CASE},
264     {"COPYRIGHT", CMD_COPYRIGHT},
265     {"CS",        CMD_CS},
266     {"DATA",      CMD_DATA},
267     {"DATE",      CMD_DATE},
268#ifndef NO_DEPRECATED
269     {"DEFAULT",   CMD_DEFAULT},
270#endif
271     {"END",       CMD_END},
272     {"ENTRANCE",  CMD_ENTRANCE},
273     {"EQUATE",    CMD_EQUATE},
274     {"EXPORT",    CMD_EXPORT},
275     {"FIX",       CMD_FIX},
276     {"FLAGS",     CMD_FLAGS},
277     {"INCLUDE",   CMD_INCLUDE},
278     {"INFER",     CMD_INFER},
279     {"INSTRUMENT",CMD_INSTRUMENT},
280#ifndef NO_DEPRECATED
281     {"PREFIX",    CMD_PREFIX},
282#endif
283     {"REQUIRE",   CMD_REQUIRE},
284     {"SD",        CMD_SD},
285     {"SET",       CMD_SET},
286     {"SOLVE",     CMD_SOLVE},
287     {"TEAM",      CMD_TEAM},
288     {"TITLE",     CMD_TITLE},
289     {"TRUNCATE",  CMD_TRUNCATE},
290     {"UNITS",     CMD_UNITS},
291     {NULL,        CMD_NULL}
292};
293
294/* masks for units which are length and angles respectively */
295#define LEN_UMASK (BIT(UNITS_METRES) | BIT(UNITS_FEET) | BIT(UNITS_YARDS))
296#define ANG_UMASK (BIT(UNITS_DEGS) | BIT(UNITS_GRADS) | BIT(UNITS_MINUTES))
297
298/* ordering must be the same as the units enum */
299const real factor_tab[] = {
300   1.0, METRES_PER_FOOT, (METRES_PER_FOOT*3.0),
301   (M_PI/180.0), (M_PI/200.0), 0.01, (M_PI/180.0/60.0)
302};
303
304const int units_to_msgno[] = {
305    /*m*/424,
306    /*ft*/428,
307    -1, /* yards */
308    /*°*/344,
309    /*ᵍ*/76,
310    /*%*/96,
311    -1 /* minutes */
312};
313
314int get_length_units(int quantity) {
315    double factor = pcs->units[quantity];
316    if (fabs(factor - METRES_PER_FOOT) <= REAL_EPSILON ||
317        fabs(factor - METRES_PER_FOOT * 3.0) <= REAL_EPSILON) {
318        return UNITS_FEET;
319    }
320    return UNITS_METRES;
321}
322
323int get_angle_units(int quantity) {
324    double factor = pcs->units[quantity];
325    if (fabs(factor - M_PI / 200.0) <= REAL_EPSILON) {
326        return UNITS_GRADS;
327    }
328    return UNITS_DEGS;
329}
330
331static int
332get_units(unsigned long qmask, bool percent_ok)
333{
334   static const sztok utab[] = {
335        {"DEGREES",       UNITS_DEGS },
336        {"DEGS",          UNITS_DEGS },
337        {"FEET",          UNITS_FEET },
338        {"GRADS",         UNITS_GRADS },
339        {"METERS",        UNITS_METRES },
340        {"METRES",        UNITS_METRES },
341        {"METRIC",        UNITS_METRES },
342        {"MILS",          UNITS_GRADS },
343        {"MINUTES",       UNITS_MINUTES },
344        {"PERCENT",       UNITS_PERCENT },
345        {"PERCENTAGE",    UNITS_PERCENT },
346        {"YARDS",         UNITS_YARDS },
347        {NULL,            UNITS_NULL }
348   };
349   int units;
350   get_token();
351   units = match_tok(utab, TABSIZE(utab));
352   if (units == UNITS_NULL) {
353      file.lpos += strlen(buffer);
354      compile_error_skip(-/*Unknown units “%s”*/35, buffer);
355      return UNITS_NULL;
356   }
357   if (units == UNITS_PERCENT && percent_ok &&
358       !(qmask & ~(BIT(Q_GRADIENT)|BIT(Q_BACKGRADIENT)))) {
359      return units;
360   }
361   if (((qmask & LEN_QMASK) && !TSTBIT(LEN_UMASK, units)) ||
362       ((qmask & ANG_QMASK) && !TSTBIT(ANG_UMASK, units))) {
363      file.lpos += strlen(buffer);
364      /* TRANSLATORS: Note: In English you talk about the *units* of a single
365       * measurement, but the correct term in other languages may be singular.
366       */
367      compile_error_skip(-/*Invalid units “%s” for quantity*/37, buffer);
368      return UNITS_NULL;
369   }
370   return units;
371}
372
373/* returns mask with bit x set to indicate quantity x specified */
374static unsigned long
375get_qlist(unsigned long mask_bad)
376{
377   static const sztok qtab[] = {
378        {"ALTITUDE",     Q_DZ },
379        {"BACKBEARING",  Q_BACKBEARING },
380        {"BACKCLINO",    Q_BACKGRADIENT },    /* alternative name */
381        {"BACKCOMPASS",  Q_BACKBEARING },     /* alternative name */
382        {"BACKGRADIENT", Q_BACKGRADIENT },
383        {"BEARING",      Q_BEARING },
384        {"CEILING",      Q_UP },          /* alternative name */
385        {"CLINO",        Q_GRADIENT },    /* alternative name */
386        {"COMPASS",      Q_BEARING },     /* alternative name */
387        {"COUNT",        Q_COUNT },
388        {"COUNTER",      Q_COUNT },       /* alternative name */
389        {"DECLINATION",  Q_DECLINATION },
390        {"DEFAULT",      Q_DEFAULT }, /* not a real quantity... */
391        {"DEPTH",        Q_DEPTH },
392        {"DOWN",         Q_DOWN },
393        {"DX",           Q_DX },          /* alternative name */
394        {"DY",           Q_DY },          /* alternative name */
395        {"DZ",           Q_DZ },          /* alternative name */
396        {"EASTING",      Q_DX },
397        {"FLOOR",        Q_DOWN },        /* alternative name */
398        {"GRADIENT",     Q_GRADIENT },
399        {"LEFT",         Q_LEFT },
400        {"LENGTH",       Q_LENGTH },
401        {"LEVEL",        Q_LEVEL},
402        {"NORTHING",     Q_DY },
403        {"PLUMB",        Q_PLUMB},
404        {"POSITION",     Q_POS },
405        {"RIGHT",        Q_RIGHT },
406        {"TAPE",         Q_LENGTH },      /* alternative name */
407        {"UP",           Q_UP },
408        {NULL,           Q_NULL }
409   };
410   unsigned long qmask = 0;
411   int tok;
412   filepos fp;
413
414   while (1) {
415      get_pos(&fp);
416      get_token();
417      tok = match_tok(qtab, TABSIZE(qtab));
418      if (tok == Q_DEFAULT && !(mask_bad & BIT(Q_DEFAULT))) {
419          /* Only recognise DEFAULT if it is the first quantity, and then don't
420           * look for any more. */
421          if (qmask == 0)
422              return BIT(Q_DEFAULT);
423          break;
424      }
425      /* bail out if we reach the table end with no match */
426      if (tok == Q_NULL) break;
427      qmask |= BIT(tok);
428      if (qmask & mask_bad) {
429         file.lpos += strlen(buffer);
430         compile_error_skip(-/*Unknown instrument “%s”*/39, buffer);
431         return 0;
432      }
433   }
434
435   if (qmask == 0) {
436      file.lpos += strlen(buffer);
437      compile_error_skip(-/*Unknown quantity “%s”*/34, buffer);
438   } else {
439      set_pos(&fp);
440   }
441
442   return qmask;
443}
444
445#define SPECIAL_UNKNOWN 0
446static void
447cmd_set(void)
448{
449   static const sztok chartab[] = {
450        {"BLANK",     SPECIAL_BLANK },
451/*FIXME {"CLOSE",     SPECIAL_CLOSE }, */
452        {"COMMENT",   SPECIAL_COMMENT },
453        {"DECIMAL",   SPECIAL_DECIMAL },
454        {"EOL",       SPECIAL_EOL }, /* EOL won't work well */
455        {"KEYWORD",   SPECIAL_KEYWORD },
456        {"MINUS",     SPECIAL_MINUS },
457        {"NAMES",     SPECIAL_NAMES },
458        {"OMIT",      SPECIAL_OMIT },
459/*FIXME {"OPEN",      SPECIAL_OPEN }, */
460        {"PLUS",      SPECIAL_PLUS },
461#ifndef NO_DEPRECATED
462        {"ROOT",      SPECIAL_ROOT },
463#endif
464        {"SEPARATOR", SPECIAL_SEPARATOR },
465        {NULL,        SPECIAL_UNKNOWN }
466   };
467   int mask;
468   int i;
469
470   get_token();
471   mask = match_tok(chartab, TABSIZE(chartab));
472
473   if (mask == SPECIAL_UNKNOWN) {
474      file.lpos += strlen(buffer);
475      compile_error_skip(-/*Unknown character class “%s”*/42, buffer);
476      return;
477   }
478
479#ifndef NO_DEPRECATED
480   if (mask == SPECIAL_ROOT) {
481      if (root_depr_count < 5) {
482         file.lpos += strlen(buffer);
483         /* TRANSLATORS: Use of the ROOT character (which is "\" by default) is
484          * deprecated, so this error would be generated by:
485          *
486          * *equate \foo.7 1
487          *
488          * If you're unsure what "deprecated" means, see:
489          * http://en.wikipedia.org/wiki/Deprecation */
490         compile_warning(-/*ROOT is deprecated*/25);
491         if (++root_depr_count == 5)
492             /* TRANSLATORS: If you're unsure what "deprecated" means, see:
493              * http://en.wikipedia.org/wiki/Deprecation */
494            compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
495      }
496   }
497#endif
498
499   /* if we're currently using an inherited translation table, allocate a new
500    * table, and copy old one into it */
501   if (pcs->next && pcs->next->Translate == pcs->Translate) {
502      short *p;
503      p = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
504      memcpy(p - 1, pcs->Translate - 1, sizeof(short) * 257);
505      pcs->Translate = p;
506   }
507
508   skipblanks();
509
510   /* clear this flag for all non-alphanums */
511   for (i = 0; i < 256; i++)
512      if (!isalnum(i)) pcs->Translate[i] &= ~mask;
513
514   /* now set this flag for all specified chars */
515   while (!isEol(ch)) {
516      if (!isalnum(ch)) {
517         pcs->Translate[ch] |= mask;
518      } else if (tolower(ch) == 'x') {
519         int hex;
520         filepos fp;
521         get_pos(&fp);
522         nextch();
523         if (!isxdigit(ch)) {
524            set_pos(&fp);
525            break;
526         }
527         hex = isdigit(ch) ? ch - '0' : tolower(ch) - 'a';
528         nextch();
529         if (!isxdigit(ch)) {
530            set_pos(&fp);
531            break;
532         }
533         hex = hex << 4 | (isdigit(ch) ? ch - '0' : tolower(ch) - 'a');
534         pcs->Translate[hex] |= mask;
535      } else {
536         break;
537      }
538      nextch();
539   }
540}
541
542static void
543check_reentry(prefix *survey)
544{
545   /* Don't try to check "*prefix \" or "*begin \" */
546   if (!survey->up) return;
547   if (TSTBIT(survey->sflags, SFLAGS_PREFIX_ENTERED)) {
548      static int reenter_depr_count = 0;
549
550      if (reenter_depr_count >= 5)
551         return;
552
553      /* TRANSLATORS: e.g.
554       *
555       * *begin crawl
556       * 1 2 9.45 234 -01
557       * *end crawl
558       * *begin crawl    # <- warning here
559       * 2 3 7.67 223 -03
560       * *end crawl
561       *
562       * If you're unsure what "deprecated" means, see:
563       * http://en.wikipedia.org/wiki/Deprecation */
564      compile_warning(/*Reentering an existing survey is deprecated*/29);
565      compile_warning_pfx(survey, /*Originally entered here*/30);
566      if (++reenter_depr_count == 5)
567         compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
568   } else {
569      survey->sflags |= BIT(SFLAGS_PREFIX_ENTERED);
570      survey->filename = file.filename;
571      survey->line = file.line;
572   }
573}
574
575#ifndef NO_DEPRECATED
576static void
577cmd_prefix(void)
578{
579   static int prefix_depr_count = 0;
580   prefix *survey;
581   /* Issue warning first, so "*prefix \" warns first that *prefix is
582    * deprecated and then that ROOT is...
583    */
584   if (prefix_depr_count < 5) {
585      /* TRANSLATORS: If you're unsure what "deprecated" means, see:
586       * http://en.wikipedia.org/wiki/Deprecation */
587      compile_warning(-/**prefix is deprecated - use *begin and *end instead*/6);
588      if (++prefix_depr_count == 5)
589         compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
590   }
591   survey = read_prefix(PFX_SURVEY|PFX_ALLOW_ROOT);
592   pcs->Prefix = survey;
593   check_reentry(survey);
594}
595#endif
596
597static void
598cmd_alias(void)
599{
600   /* Currently only two forms are supported:
601    * *alias station - ..
602    * *alias station -
603    */
604   get_token();
605   if (strcmp(ucbuffer, "STATION") != 0)
606      goto bad;
607   get_word();
608   if (strcmp(buffer, "-") != 0)
609      goto bad;
610   get_word();
611   if (*buffer && strcmp(buffer, "..") != 0)
612      goto bad;
613   pcs->dash_for_anon_wall_station = (*buffer != '\0');
614   return;
615bad:
616   compile_error_skip(/*Bad *alias command*/397);
617}
618
619static void
620cmd_begin(void)
621{
622   prefix *survey;
623   settings *pcsNew;
624
625   pcsNew = osnew(settings);
626   *pcsNew = *pcs; /* copy contents */
627   pcsNew->begin_lineno = file.line;
628   pcsNew->next = pcs;
629   pcs = pcsNew;
630
631   survey = read_prefix(PFX_SURVEY|PFX_OPT|PFX_ALLOW_ROOT|PFX_WARN_SEPARATOR);
632   pcs->begin_survey = survey;
633   if (survey) {
634      pcs->Prefix = survey;
635      check_reentry(survey);
636      f_export_ok = fTrue;
637   }
638}
639
640extern void
641free_settings(settings *p) {
642   /* don't free default ordering or ordering used by parent */
643   reading *order = p->ordering;
644   if (order != default_order && (!p->next || order != p->next->ordering))
645      osfree(order);
646
647   /* free Translate if not used by parent */
648   if (!p->next || p->Translate != p->next->Translate)
649      osfree(p->Translate - 1);
650
651   /* free meta if not used by parent, or in this block */
652   if (p->meta && (!p->next || p->meta != p->next->meta) && p->meta->ref_count == 0)
653       osfree(p->meta);
654
655   /* free proj if not used by parent, or as the output projection */
656   if (p->proj && (!p->next || p->proj != p->next->proj) && p->proj != proj_out)
657       pj_free(p->proj);
658
659   osfree(p);
660}
661
662static void
663cmd_end(void)
664{
665   settings *pcsParent;
666   prefix *survey, *begin_survey;
667
668   pcsParent = pcs->next;
669
670   if (pcs->begin_lineno == 0) {
671      if (pcsParent == NULL) {
672         /* more ENDs than BEGINs */
673         compile_error_skip(/*No matching BEGIN*/192);
674      } else {
675         compile_error_skip(/*END with no matching BEGIN in this file*/22);
676      }
677      return;
678   }
679
680   begin_survey = pcs->begin_survey;
681
682   SVX_ASSERT(pcsParent);
683   free_settings(pcs);
684   pcs = pcsParent;
685
686   /* note need to read using root *before* BEGIN */
687   survey = read_prefix(PFX_SURVEY|PFX_OPT|PFX_ALLOW_ROOT);
688   if (survey != begin_survey) {
689      if (survey) {
690         if (!begin_survey) {
691            /* TRANSLATORS: Used when a BEGIN command has no survey, but the
692             * END command does, e.g.:
693             *
694             * *begin
695             * 1 2 10.00 178 -01
696             * *end entrance      <--[Message given here] */
697            compile_error_skip(-/*Matching BEGIN command has no survey name*/36);
698         } else {
699            /* TRANSLATORS: *BEGIN <survey> and *END <survey> should have the
700             * same <survey> if it’s given at all */
701            compile_error_skip(-/*Survey name doesn’t match BEGIN*/193);
702         }
703      } else {
704         /* TRANSLATORS: Used when a BEGIN command has a survey name, but the
705          * END command omits it, e.g.:
706          *
707          * *begin entrance
708          * 1 2 10.00 178 -01
709          * *end     <--[Message given here] */
710         compile_warning(-/*Survey name omitted from END*/194);
711      }
712   }
713}
714
715static void
716cmd_entrance(void)
717{
718   prefix *pfx = read_prefix(PFX_STATION);
719   pfx->sflags |= BIT(SFLAGS_ENTRANCE);
720}
721
722static const prefix * first_fix_name = NULL;
723static const char * first_fix_filename;
724static unsigned first_fix_line;
725
726static void
727cmd_fix(void)
728{
729   prefix *fix_name;
730   node *stn = NULL;
731   static prefix *name_omit_already = NULL;
732   static const char * name_omit_already_filename = NULL;
733   static unsigned int name_omit_already_line;
734   real x, y, z;
735   int nx, ny, nz;
736   filepos fp;
737
738   fix_name = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
739   fix_name->sflags |= BIT(SFLAGS_FIXED);
740
741   get_pos(&fp);
742   get_token();
743   if (strcmp(ucbuffer, "REFERENCE") == 0) {
744      /* suppress "unused fixed point" warnings for this station */
745      fix_name->sflags |= BIT(SFLAGS_USED);
746   } else {
747      if (*ucbuffer) set_pos(&fp);
748   }
749
750   x = read_numeric(fTrue, &nx);
751   if (x == HUGE_REAL) {
752      /* If the end of the line isn't blank, read a number after all to
753       * get a more helpful error message */
754      if (!isEol(ch) && !isComm(ch)) x = read_numeric(fFalse, &nx);
755   }
756   if (x == HUGE_REAL) {
757      if (pcs->proj || proj_out) {
758         compile_error_skip(/*Coordinates can't be omitted when coordinate system has been specified*/439);
759         return;
760      }
761
762      if (fix_name == name_omit_already) {
763         compile_warning(/*Same station fixed twice with no coordinates*/61);
764         return;
765      }
766
767      /* TRANSLATORS: " *fix a " gives this message: */
768      compile_warning(/*FIX command with no coordinates - fixing at (0,0,0)*/54);
769
770      if (name_omit_already) {
771         /* TRANSLATORS: Emitted after second and subsequent "FIX command with
772          * no coordinates - fixing at (0,0,0)" warnings.
773          */
774         compile_error_at(name_omit_already_filename,
775                          name_omit_already_line,
776                          /*Already had FIX command with no coordinates for station “%s”*/441,
777                          sprint_prefix(name_omit_already));
778      } else {
779         name_omit_already = fix_name;
780         name_omit_already_filename = file.filename;
781         name_omit_already_line = file.line;
782      }
783
784      x = y = z = (real)0.0;
785   } else {
786      real sdx;
787      y = read_numeric(fFalse, &ny);
788      z = read_numeric(fFalse, &nz);
789      sdx = read_numeric(fTrue, NULL);
790      if (sdx != HUGE_REAL) {
791         real sdy, sdz;
792         real cxy = 0, cyz = 0, czx = 0;
793         sdy = read_numeric(fTrue, NULL);
794         if (sdy == HUGE_REAL) {
795            /* only one variance given */
796            sdy = sdz = sdx;
797         } else {
798            sdz = read_numeric(fTrue, NULL);
799            if (sdz == HUGE_REAL) {
800               /* two variances given - horizontal & vertical */
801               sdz = sdy;
802               sdy = sdx;
803            } else {
804               cxy = read_numeric(fTrue, NULL);
805               if (cxy != HUGE_REAL) {
806                  /* covariances given */
807                  cyz = read_numeric(fFalse, NULL);
808                  czx = read_numeric(fFalse, NULL);
809               } else {
810                  cxy = 0;
811               }
812            }
813         }
814         stn = StnFromPfx(fix_name);
815         if (!fixed(stn)) {
816            node *fixpt = osnew(node);
817            prefix *name;
818            name = osnew(prefix);
819            name->pos = osnew(pos);
820            name->ident = NULL;
821            name->shape = 0;
822            fixpt->name = name;
823            name->stn = fixpt;
824            name->up = NULL;
825            if (TSTBIT(pcs->infer, INFER_EXPORTS)) {
826               name->min_export = USHRT_MAX;
827            } else {
828               name->min_export = 0;
829            }
830            name->max_export = 0;
831            name->sflags = 0;
832            add_stn_to_list(&stnlist, fixpt);
833            POS(fixpt, 0) = x;
834            POS(fixpt, 1) = y;
835            POS(fixpt, 2) = z;
836            fix(fixpt);
837            fixpt->leg[0] = fixpt->leg[1] = fixpt->leg[2] = NULL;
838            addfakeleg(fixpt, stn, 0, 0, 0,
839                       sdx * sdx, sdy * sdy, sdz * sdz
840#ifndef NO_COVARIANCES
841                       , cxy, cyz, czx
842#endif
843                       );
844         }
845         return;
846      }
847
848      if (pcs->proj && proj_out) {
849         int r = pj_transform(pcs->proj, proj_out, 1, 1, &x, &y, &z);
850         if (r != 0) {
851            compile_error(/*Failed to convert coordinates*/436);
852            /* FIXME: report pj_strerrno(r) */
853            printf("[%s]\n", pj_strerrno(r));
854         }
855      } else if (pcs->proj) {
856         compile_error(/*The input projection is set but the output projection isn't*/437);
857      } else if (proj_out) {
858         compile_error(/*The output projection is set but the input projection isn't*/438);
859      }
860   }
861
862   if (!first_fix_name) {
863      /* We track if we've fixed a station yet, and if so what the name of the
864       * first fix was, so that we can issue an error if the output coordinate
865       * system is set after fixing a station. */
866      first_fix_name = fix_name;
867      first_fix_filename = file.filename;
868      first_fix_line = file.line;
869   }
870
871   stn = StnFromPfx(fix_name);
872   if (!fixed(stn)) {
873      POS(stn, 0) = x;
874      POS(stn, 1) = y;
875      POS(stn, 2) = z;
876      fix(stn);
877      return;
878   }
879
880   if (x != POS(stn, 0) || y != POS(stn, 1) || z != POS(stn, 2)) {
881      compile_error(/*Station already fixed or equated to a fixed point*/46);
882      return;
883   }
884   /* TRANSLATORS: *fix a 1 2 3 / *fix a 1 2 3 */
885   compile_warning(/*Station already fixed at the same coordinates*/55);
886}
887
888static void
889cmd_flags(void)
890{
891   static const sztok flagtab[] = {
892        {"DUPLICATE", FLAGS_DUPLICATE },
893        {"NOT",       FLAGS_NOT },
894        {"SPLAY",     FLAGS_SPLAY },
895        {"SURFACE",   FLAGS_SURFACE },
896        {NULL,        FLAGS_UNKNOWN }
897   };
898   bool fNot = fFalse;
899   bool fEmpty = fTrue;
900   while (1) {
901      int flag;
902      get_token();
903      /* If buffer is empty, it could mean end of line, or maybe
904       * some non-letter junk which is better reported later */
905      if (!buffer[0]) break;
906
907      fEmpty = fFalse;
908      flag = match_tok(flagtab, TABSIZE(flagtab));
909      /* treat the second NOT in "NOT NOT" as an unknown flag */
910      if (flag == FLAGS_UNKNOWN || (fNot && flag == FLAGS_NOT)) {
911         file.lpos += strlen(buffer);
912         compile_error(-/*FLAG “%s” unknown*/68, buffer);
913         /* Recover from “*FLAGS NOT BOGUS SURFACE” by ignoring "NOT BOGUS" */
914         fNot = fFalse;
915      } else if (flag == FLAGS_NOT) {
916         fNot = fTrue;
917      } else if (fNot) {
918         pcs->flags &= ~BIT(flag);
919         fNot = fFalse;
920      } else {
921         pcs->flags |= BIT(flag);
922      }
923   }
924
925   if (fNot) {
926      file.lpos += strlen(buffer);
927      compile_error(-/*Expecting “DUPLICATE”, “SPLAY”, or “SURFACE”*/188);
928   } else if (fEmpty) {
929      file.lpos += strlen(buffer);
930      compile_error(-/*Expecting “NOT”, “DUPLICATE”, “SPLAY”, or “SURFACE”*/189);
931   }
932}
933
934static void
935cmd_equate(void)
936{
937   prefix *name1, *name2;
938   bool fOnlyOneStn = fTrue; /* to trap eg *equate entrance.6 */
939
940   name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO);
941   while (fTrue) {
942      name2 = name1;
943      name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO|PFX_OPT);
944      if (name1 == NULL) {
945         if (fOnlyOneStn) {
946            /* TRANSLATORS: EQUATE is a command name, so shouldn’t be
947             * translated.
948             *
949             * Here "station" is a survey station, not a train station.
950             */
951            compile_error_skip(-/*Only one station in EQUATE command*/33);
952         }
953         return;
954      }
955
956      process_equate(name1, name2);
957      fOnlyOneStn = fFalse;
958   }
959}
960
961static void
962report_missing_export(prefix *pfx, int depth)
963{
964   char *s;
965   const char *p;
966   prefix *survey = pfx;
967   int i;
968   for (i = depth + 1; i; i--) {
969      survey = survey->up;
970      SVX_ASSERT(survey);
971   }
972   s = osstrdup(sprint_prefix(survey));
973   p = sprint_prefix(pfx);
974   if (survey->filename) {
975      /* TRANSLATORS: A station must be exported out of each level it is in, so
976       * this would give "Station “\outer.inner.1” not exported from survey
977       * “\outer”)":
978       *
979       * *equate entrance outer.inner.1
980       * *begin outer
981       * *begin inner
982       * *export 1
983       * 1 2 1.23 045 -6
984       * *end inner
985       * *end outer
986       *
987       * Here "survey" is a "cave map" rather than list of questions - it should be
988       * translated to the terminology that cavers using the language would use.
989       */
990      compile_error_pfx(survey,
991                        /*Station “%s” not exported from survey “%s”*/26, p, s);
992   } else {
993      compile_error(/*Station “%s” not exported from survey “%s”*/26, p, s);
994   }
995   osfree(s);
996}
997
998static void
999cmd_export(void)
1000{
1001   prefix *pfx;
1002
1003   fExportUsed = fTrue;
1004   pfx = read_prefix(PFX_STATION);
1005   do {
1006      int depth = 0;
1007      {
1008         prefix *p = pfx;
1009         while (p != NULL && p != pcs->Prefix) {
1010            depth++;
1011            p = p->up;
1012         }
1013         /* Something like: *export \foo, but we've excluded use of root */
1014         SVX_ASSERT(p);
1015      }
1016      /* *export \ or similar bogus stuff */
1017      SVX_ASSERT(depth);
1018#if 0
1019      printf("C min %d max %d depth %d pfx %s\n",
1020             pfx->min_export, pfx->max_export, depth, sprint_prefix(pfx));
1021#endif
1022      if (pfx->min_export == 0) {
1023         /* not encountered *export for this name before */
1024         if (pfx->max_export > depth) report_missing_export(pfx, depth);
1025         pfx->min_export = pfx->max_export = depth;
1026      } else if (pfx->min_export != USHRT_MAX) {
1027         /* FIXME: what to do if a station is marked for inferred exports
1028          * but is then explicitly exported?  Currently we just ignore the
1029          * explicit export... */
1030         if (pfx->min_export - 1 > depth) {
1031            report_missing_export(pfx, depth);
1032         } else if (pfx->min_export - 1 < depth) {
1033            /* TRANSLATORS: Here "station" is a survey station, not a train station.
1034             *
1035             * Exporting a station twice gives this error:
1036             *
1037             * *begin example
1038             * *export 1
1039             * *export 1
1040             * 1 2 1.24 045 -6
1041             * *end example */
1042            compile_error(/*Station “%s” already exported*/66,
1043                          sprint_prefix(pfx));
1044         }
1045         pfx->min_export = depth;
1046      }
1047      pfx = read_prefix(PFX_STATION|PFX_OPT);
1048   } while (pfx);
1049}
1050
1051static void
1052cmd_data(void)
1053{
1054   static const sztok dtab[] = {
1055        {"ALTITUDE",     Dz },
1056        {"BACKBEARING",  BackComp },
1057        {"BACKCLINO",    BackClino }, /* alternative name */
1058        {"BACKCOMPASS",  BackComp }, /* alternative name */
1059        {"BACKGRADIENT", BackClino },
1060        {"BEARING",      Comp },
1061        {"CEILING",      Up }, /* alternative name */
1062        {"CLINO",        Clino }, /* alternative name */
1063        {"COMPASS",      Comp }, /* alternative name */
1064        {"COUNT",        Count }, /* FrCount&ToCount in multiline */
1065        {"DEPTH",        Depth }, /* FrDepth&ToDepth in multiline */
1066        {"DEPTHCHANGE",  DepthChange },
1067        {"DIRECTION",    Dir },
1068        {"DOWN",         Down },
1069        {"DX",           Dx },
1070        {"DY",           Dy },
1071        {"DZ",           Dz },
1072        {"EASTING",      Dx },
1073        {"FLOOR",        Down }, /* alternative name */
1074        {"FROM",         Fr },
1075        {"FROMCOUNT",    FrCount },
1076        {"FROMDEPTH",    FrDepth },
1077        {"GRADIENT",     Clino },
1078        {"IGNORE",       Ignore },
1079        {"IGNOREALL",    IgnoreAll },
1080        {"LEFT",         Left },
1081        {"LENGTH",       Tape },
1082        {"NEWLINE",      Newline },
1083        {"NORTHING",     Dy },
1084        {"RIGHT",        Right },
1085        {"STATION",      Station }, /* Fr&To in multiline */
1086        {"TAPE",         Tape }, /* alternative name */
1087        {"TO",           To },
1088        {"TOCOUNT",      ToCount },
1089        {"TODEPTH",      ToDepth },
1090        {"UP",           Up },
1091        {NULL,           End }
1092   };
1093
1094#define MASK_stns BIT(Fr) | BIT(To) | BIT(Station)
1095#define MASK_tape BIT(Tape) | BIT(FrCount) | BIT(ToCount) | BIT(Count)
1096#define MASK_dpth BIT(FrDepth) | BIT(ToDepth) | BIT(Depth) | BIT(DepthChange)
1097#define MASK_comp BIT(Comp) | BIT(BackComp)
1098#define MASK_clin BIT(Clino) | BIT(BackClino)
1099
1100#define MASK_NORMAL MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_clin
1101#define MASK_DIVING MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_dpth
1102#define MASK_CARTESIAN MASK_stns | BIT(Dx) | BIT(Dy) | BIT(Dz)
1103#define MASK_CYLPOLAR  MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_dpth
1104#define MASK_PASSAGE BIT(Station) | BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down)
1105#define MASK_NOSURVEY MASK_stns
1106
1107   /* readings which may be given for each style */
1108   static const unsigned long mask[] = {
1109      MASK_NORMAL, MASK_DIVING, MASK_CARTESIAN, MASK_CYLPOLAR, MASK_NOSURVEY,
1110      MASK_PASSAGE
1111   };
1112
1113   /* readings which may be omitted for each style */
1114   static const unsigned long mask_optional[] = {
1115      BIT(Dir) | BIT(Clino) | BIT(BackClino),
1116      BIT(Dir),
1117      0,
1118      BIT(Dir),
1119      0,
1120      0 /* BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down), */
1121   };
1122
1123   /* all valid readings */
1124   static const unsigned long mask_all[] = {
1125      MASK_NORMAL | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1126      MASK_DIVING | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1127      MASK_CARTESIAN | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1128      MASK_CYLPOLAR | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1129      MASK_NOSURVEY | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
1130      MASK_PASSAGE | BIT(Ignore) | BIT(IgnoreAll) | BIT(End)
1131   };
1132#define STYLE_DEFAULT   -2
1133#define STYLE_UNKNOWN   -1
1134
1135   static const sztok styletab[] = {
1136        {"CARTESIAN",    STYLE_CARTESIAN },
1137        {"CYLPOLAR",     STYLE_CYLPOLAR },
1138        {"DEFAULT",      STYLE_DEFAULT },
1139        {"DIVING",       STYLE_DIVING },
1140        {"NORMAL",       STYLE_NORMAL },
1141        {"NOSURVEY",     STYLE_NOSURVEY },
1142        {"PASSAGE",      STYLE_PASSAGE },
1143        {"TOPOFIL",      STYLE_NORMAL },
1144        {NULL,           STYLE_UNKNOWN }
1145   };
1146
1147#define m_multi (BIT(Station) | BIT(Count) | BIT(Depth))
1148
1149   int style, k = 0, kMac;
1150   reading *new_order, d;
1151   unsigned long mUsed = 0;
1152   char *style_name;
1153
1154   /* after a bad *data command ignore survey data until the next
1155    * *data command to avoid an avalanche of errors */
1156   pcs->style = STYLE_IGNORE;
1157
1158   kMac = 6; /* minimum for NORMAL style */
1159   new_order = osmalloc(kMac * sizeof(reading));
1160
1161   get_token();
1162   style = match_tok(styletab, TABSIZE(styletab));
1163
1164   if (style == STYLE_DEFAULT) {
1165      default_style(pcs);
1166      return;
1167   }
1168
1169   if (style == STYLE_UNKNOWN) {
1170      file.lpos += strlen(buffer);
1171      /* TRANSLATORS: e.g. trying to refer to an invalid FNORD data style */
1172      compile_error_skip(-/*Data style “%s” unknown*/65, buffer);
1173      return;
1174   }
1175
1176   skipblanks();
1177#ifndef NO_DEPRECATED
1178   /* Olde syntax had optional field for survey grade, so allow an omit
1179    * but issue a warning about it */
1180   if (isOmit(ch)) {
1181      static int data_depr_count = 0;
1182      if (data_depr_count < 5) {
1183         file.lpos += strlen(buffer);
1184         compile_warning(-/*“*data %s %c …” is deprecated - use “*data %s …” instead*/104,
1185                         buffer, ch, buffer);
1186         if (++data_depr_count == 5)
1187            compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
1188      }
1189      nextch();
1190   }
1191#endif
1192
1193   style_name = osstrdup(buffer);
1194   do {
1195      filepos fp;
1196      get_pos(&fp);
1197      get_token();
1198      d = match_tok(dtab, TABSIZE(dtab));
1199      /* only token allowed after IGNOREALL is NEWLINE */
1200      if (k && new_order[k - 1] == IgnoreAll && d != Newline) {
1201         set_pos(&fp);
1202         break;
1203      }
1204      /* Note: an unknown token is reported as trailing garbage */
1205      if (!TSTBIT(mask_all[style], d)) {
1206         file.lpos += strlen(buffer);
1207         /* TRANSLATORS: a data "style" is something like NORMAL, DIVING, etc.
1208          * a "reading" is one of FROM, TO, TAPE, COMPASS, CLINO for NORMAL
1209          * neither style nor reading is a keyword in the program This error
1210          * complains about a depth gauge reading in normal style, for example
1211          */
1212         compile_error_skip(-/*Reading “%s” not allowed in data style “%s”*/63,
1213                       buffer, style_name);
1214         osfree(style_name);
1215         osfree(new_order);
1216         return;
1217      }
1218      if (TSTBIT(mUsed, Newline) && TSTBIT(m_multi, d)) {
1219         file.lpos += strlen(buffer);
1220         /* TRANSLATORS: caused by e.g.
1221          *
1222          * *data diving station newline depth tape compass
1223          *
1224          * ("depth" needs to occur before "newline"). */
1225         compile_error_skip(-/*Reading “%s” must occur before NEWLINE*/225, buffer);
1226         osfree(style_name);
1227         osfree(new_order);
1228         return;
1229      }
1230      /* Check for duplicates unless it's a special reading:
1231       *   IGNOREALL,IGNORE (duplicates allowed) ; END (not possible)
1232       */
1233      if (!((BIT(Ignore) | BIT(End) | BIT(IgnoreAll)) & BIT(d))) {
1234         if (TSTBIT(mUsed, d)) {
1235            file.lpos += strlen(buffer);
1236            /* TRANSLATORS: complains about a situation like trying to define
1237             * two from stations per leg */
1238            compile_error_skip(-/*Duplicate reading “%s”*/67, buffer);
1239            osfree(style_name);
1240            osfree(new_order);
1241            return;
1242         } else {
1243            /* Check for previously listed readings which are incompatible
1244             * with this one - e.g. Count vs FrCount */
1245            bool fBad = fFalse;
1246            switch (d) {
1247             case Station:
1248               if (mUsed & (BIT(Fr) | BIT(To))) fBad = fTrue;
1249               break;
1250             case Fr: case To:
1251               if (TSTBIT(mUsed, Station)) fBad = fTrue;
1252               break;
1253             case Count:
1254               if (mUsed & (BIT(FrCount) | BIT(ToCount) | BIT(Tape)))
1255                  fBad = fTrue;
1256               break;
1257             case FrCount: case ToCount:
1258               if (mUsed & (BIT(Count) | BIT(Tape)))
1259                  fBad = fTrue;
1260               break;
1261             case Depth:
1262               if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(DepthChange)))
1263                  fBad = fTrue;
1264               break;
1265             case FrDepth: case ToDepth:
1266               if (mUsed & (BIT(Depth) | BIT(DepthChange))) fBad = fTrue;
1267               break;
1268             case DepthChange:
1269               if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(Depth)))
1270                  fBad = fTrue;
1271               break;
1272             case Newline:
1273               if (mUsed & ~m_multi) {
1274                  file.lpos += strlen(buffer);
1275                  /* TRANSLATORS: e.g.
1276                   *
1277                   * *data normal from to tape newline compass clino */
1278                  compile_error_skip(-/*NEWLINE can only be preceded by STATION, DEPTH, and COUNT*/226);
1279                  osfree(style_name);
1280                  osfree(new_order);
1281                  return;
1282               }
1283               if (k == 0) {
1284                  file.lpos += strlen(buffer);
1285                  /* TRANSLATORS: error from:
1286                   *
1287                   * *data normal newline from to tape compass clino */
1288                  compile_error_skip(-/*NEWLINE can’t be the first reading*/222);
1289                  osfree(style_name);
1290                  osfree(new_order);
1291                  return;
1292               }
1293               break;
1294             default: /* avoid compiler warnings about unhandled enums */
1295               break;
1296            }
1297            if (fBad) {
1298               /* Not entirely happy with phrasing this... */
1299               file.lpos += strlen(buffer);
1300               compile_error_skip(-/*Reading “%s” duplicates previous reading(s)*/77,
1301                             buffer);
1302               osfree(style_name);
1303               osfree(new_order);
1304               return;
1305            }
1306            mUsed |= BIT(d); /* used to catch duplicates */
1307         }
1308      }
1309      if (k && new_order[k - 1] == IgnoreAll) {
1310         SVX_ASSERT(d == Newline);
1311         k--;
1312         d = IgnoreAllAndNewLine;
1313      }
1314      if (k >= kMac) {
1315         kMac = kMac * 2;
1316         new_order = osrealloc(new_order, kMac * sizeof(reading));
1317      }
1318      new_order[k++] = d;
1319   } while (d != End);
1320
1321   if (k >= 2 && new_order[k - 2] == Newline) {
1322      file.lpos += strlen(buffer);
1323      /* TRANSLATORS: error from:
1324       *
1325       * *data normal from to tape compass clino newline */
1326      compile_error_skip(-/*NEWLINE can’t be the last reading*/223);
1327      osfree(style_name);
1328      osfree(new_order);
1329      return;
1330   }
1331
1332   if (style == STYLE_NOSURVEY) {
1333      if (TSTBIT(mUsed, Station)) {
1334         if (k >= kMac) {
1335            kMac = kMac * 2;
1336            new_order = osrealloc(new_order, kMac * sizeof(reading));
1337         }
1338         new_order[k - 1] = Newline;
1339         new_order[k++] = End;
1340      }
1341   } else if (style == STYLE_PASSAGE) {
1342      /* Station doesn't mean "multiline" for STYLE_PASSAGE. */
1343   } else if (!TSTBIT(mUsed, Newline) && (m_multi & mUsed)) {
1344      /* TRANSLATORS: Error given by something like:
1345       *
1346       * *data normal station tape compass clino
1347       *
1348       * ("station" signifies interleaved data). */
1349      compile_error_skip(/*Interleaved readings, but no NEWLINE*/224);
1350      osfree(style_name);
1351      osfree(new_order);
1352      return;
1353   }
1354
1355#if 0
1356   printf("mUsed = 0x%x\n", mUsed);
1357#endif
1358
1359   /* Check the supplied readings form a sufficient set. */
1360   if (style != STYLE_PASSAGE) {
1361       if (mUsed & (BIT(Fr) | BIT(To)))
1362           mUsed |= BIT(Station);
1363       else if (TSTBIT(mUsed, Station))
1364           mUsed |= BIT(Fr) | BIT(To);
1365   }
1366
1367   if (mUsed & (BIT(Comp) | BIT(BackComp)))
1368      mUsed |= BIT(Comp) | BIT(BackComp);
1369
1370   if (mUsed & (BIT(Clino) | BIT(BackClino)))
1371      mUsed |= BIT(Clino) | BIT(BackClino);
1372
1373   if (mUsed & (BIT(FrDepth) | BIT(ToDepth)))
1374      mUsed |= BIT(Depth) | BIT(DepthChange);
1375   else if (TSTBIT(mUsed, Depth))
1376      mUsed |= BIT(FrDepth) | BIT(ToDepth) | BIT(DepthChange);
1377   else if (TSTBIT(mUsed, DepthChange))
1378      mUsed |= BIT(FrDepth) | BIT(ToDepth) | BIT(Depth);
1379
1380   if (mUsed & (BIT(FrCount) | BIT(ToCount)))
1381      mUsed |= BIT(Count) | BIT(Tape);
1382   else if (TSTBIT(mUsed, Count))
1383      mUsed |= BIT(FrCount) | BIT(ToCount) | BIT(Tape);
1384   else if (TSTBIT(mUsed, Tape))
1385      mUsed |= BIT(FrCount) | BIT(ToCount) | BIT(Count);
1386
1387#if 0
1388   printf("mUsed = 0x%x, opt = 0x%x, mask = 0x%x\n", mUsed,
1389          mask_optional[style], mask[style]);
1390#endif
1391
1392   if (((mUsed &~ BIT(Newline)) | mask_optional[style]) != mask[style]) {
1393      /* Test should only fail with too few bits set, not too many */
1394      SVX_ASSERT((((mUsed &~ BIT(Newline)) | mask_optional[style])
1395              &~ mask[style]) == 0);
1396      /* TRANSLATORS: i.e. not enough readings for the style. */
1397      compile_error_skip(/*Too few readings for data style “%s”*/64, style_name);
1398      osfree(style_name);
1399      osfree(new_order);
1400      return;
1401   }
1402
1403   /* don't free default ordering or ordering used by parent */
1404   if (pcs->ordering != default_order &&
1405       !(pcs->next && pcs->next->ordering == pcs->ordering))
1406      osfree(pcs->ordering);
1407
1408   pcs->style = style;
1409   pcs->ordering = new_order;
1410
1411   osfree(style_name);
1412
1413   if (style == STYLE_PASSAGE) {
1414      lrudlist * new_psg = osnew(lrudlist);
1415      new_psg->tube = NULL;
1416      new_psg->next = model;
1417      model = new_psg;
1418      next_lrud = &(new_psg->tube);
1419   }
1420}
1421
1422static void
1423cmd_units(void)
1424{
1425   int units, quantity;
1426   unsigned long qmask;
1427   unsigned long m; /* mask with bit x set to indicate quantity x specified */
1428   real factor;
1429
1430   qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1431
1432   if (!qmask) return;
1433   if (qmask == BIT(Q_DEFAULT)) {
1434      default_units(pcs);
1435      return;
1436   }
1437
1438   factor = read_numeric(fTrue, NULL);
1439   if (factor == 0.0) {
1440      /* TRANSLATORS: error message given by "*units tape 0 feet" - it’s
1441       * meaningless to say your tape is marked in "0 feet" (but you might
1442       * measure distance by counting knots on a diving line, and tie them
1443       * every "2 feet"). */
1444      compile_error_skip(-/**UNITS factor must be non-zero*/200);
1445      return;
1446   }
1447
1448   units = get_units(qmask, fTrue);
1449   if (units == UNITS_NULL) return;
1450   if (TSTBIT(qmask, Q_GRADIENT))
1451      pcs->f_clino_percent = (units == UNITS_PERCENT);
1452   if (TSTBIT(qmask, Q_BACKGRADIENT))
1453      pcs->f_backclino_percent = (units == UNITS_PERCENT);
1454
1455   if (factor == HUGE_REAL) {
1456      factor = factor_tab[units];
1457   } else {
1458      factor *= factor_tab[units];
1459   }
1460
1461   for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1462      if (qmask & m) pcs->units[quantity] = factor;
1463}
1464
1465static void
1466cmd_calibrate(void)
1467{
1468   real sc, z;
1469   unsigned long qmask, m;
1470   int quantity;
1471
1472   qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1473   if (!qmask) return; /* error already reported */
1474
1475   if (qmask == BIT(Q_DEFAULT)) {
1476      default_calib(pcs);
1477      return;
1478   }
1479
1480   if (((qmask & LEN_QMASK)) && ((qmask & ANG_QMASK))) {
1481      /* TRANSLATORS: e.g.
1482       *
1483       * *calibrate tape compass 1 1
1484       */
1485      compile_error_skip(/*Can’t calibrate angular and length quantities together*/227);
1486      return;
1487   }
1488
1489   z = read_numeric(fFalse, NULL);
1490   sc = read_numeric(fTrue, NULL);
1491   if (sc == HUGE_REAL) sc = (real)1.0;
1492   /* check for declination scale */
1493   /* perhaps "*calibrate declination XXX" should be "*declination XXX" ? */
1494   if (TSTBIT(qmask, Q_DECLINATION) && sc != 1.0) {
1495      /* TRANSLATORS: DECLINATION is a built-in keyword, so best not to
1496       * translate */
1497      compile_error_skip(-/*Scale factor must be 1.0 for DECLINATION*/40);
1498      return;
1499   }
1500   if (sc == 0.0) {
1501      /* TRANSLATORS: If the scale factor for an instrument is zero, then any
1502       * reading would be mapped to zero, which doesn't make sense. */
1503      compile_error_skip(-/*Scale factor must be non-zero*/391);
1504      return;
1505   }
1506   for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1) {
1507      if (qmask & m) {
1508         pcs->z[quantity] = pcs->units[quantity] * z;
1509         pcs->sc[quantity] = sc;
1510      }
1511   }
1512}
1513
1514#ifndef NO_DEPRECATED
1515static void
1516cmd_default(void)
1517{
1518   static const sztok defaulttab[] = {
1519      { "CALIBRATE", CMD_CALIBRATE },
1520      { "DATA",      CMD_DATA },
1521      { "UNITS",     CMD_UNITS },
1522      { NULL,        CMD_NULL }
1523   };
1524   static int default_depr_count = 0;
1525
1526   if (default_depr_count < 5) {
1527      /* TRANSLATORS: If you're unsure what "deprecated" means, see:
1528       * http://en.wikipedia.org/wiki/Deprecation */
1529      compile_warning(-/**DEFAULT is deprecated - use *CALIBRATE/DATA/SD/UNITS with argument DEFAULT instead*/20);
1530      if (++default_depr_count == 5)
1531         compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
1532   }
1533
1534   get_token();
1535   switch (match_tok(defaulttab, TABSIZE(defaulttab))) {
1536    case CMD_CALIBRATE:
1537      default_calib(pcs);
1538      break;
1539    case CMD_DATA:
1540      default_style(pcs);
1541      default_grade(pcs);
1542      break;
1543    case CMD_UNITS:
1544      default_units(pcs);
1545      break;
1546    default:
1547      file.lpos += strlen(buffer);
1548      compile_error_skip(-/*Unknown setting “%s”*/41, buffer);
1549   }
1550}
1551#endif
1552
1553static void
1554cmd_include(void)
1555{
1556   char *pth, *fnm = NULL;
1557   int fnm_len;
1558#ifndef NO_DEPRECATED
1559   prefix *root_store;
1560#endif
1561   int ch_store;
1562
1563   pth = path_from_fnm(file.filename);
1564
1565   read_string(&fnm, &fnm_len);
1566
1567#ifndef NO_DEPRECATED
1568   /* Since *begin / *end nesting cannot cross file boundaries we only
1569    * need to preserve the prefix if the deprecated *prefix command
1570    * can be used */
1571   root_store = root;
1572   root = pcs->Prefix; /* Root for include file is current prefix */
1573#endif
1574   ch_store = ch;
1575
1576   data_file(pth, fnm);
1577
1578#ifndef NO_DEPRECATED
1579   root = root_store; /* and restore root */
1580#endif
1581   ch = ch_store;
1582
1583   s_free(&fnm);
1584   osfree(pth);
1585}
1586
1587static void
1588cmd_sd(void)
1589{
1590   real sd, variance;
1591   int units;
1592   unsigned long qmask, m;
1593   int quantity;
1594   qmask = get_qlist(BIT(Q_DECLINATION));
1595   if (!qmask) return; /* no quantities found - error already reported */
1596
1597   if (qmask == BIT(Q_DEFAULT)) {
1598      default_grade(pcs);
1599      return;
1600   }
1601   sd = read_numeric(fFalse, NULL);
1602   if (sd <= (real)0.0) {
1603      compile_error_skip(-/*Standard deviation must be positive*/48);
1604      return;
1605   }
1606   units = get_units(qmask, fFalse);
1607   if (units == UNITS_NULL) return;
1608
1609   sd *= factor_tab[units];
1610   variance = sqrd(sd);
1611
1612   for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1613      if (qmask & m) pcs->Var[quantity] = variance;
1614}
1615
1616static void
1617cmd_title(void)
1618{
1619   if (!fExplicitTitle && pcs->Prefix == root) {
1620       /* If we don't have an explicit title yet, and we're currently in the
1621        * root prefix, use this title explicitly. */
1622      fExplicitTitle = fTrue;
1623      read_string(&survey_title, &survey_title_len);
1624   } else {
1625      /* parse and throw away this title (but still check rest of line) */
1626      char *s = NULL;
1627      int len;
1628      read_string(&s, &len);
1629      s_free(&s);
1630   }
1631}
1632
1633static const sztok case_tab[] = {
1634     {"PRESERVE", OFF},
1635     {"TOLOWER",  LOWER},
1636     {"TOUPPER",  UPPER},
1637     {NULL,       -1}
1638};
1639
1640static void
1641cmd_case(void)
1642{
1643   int setting;
1644   get_token();
1645   setting = match_tok(case_tab, TABSIZE(case_tab));
1646   if (setting != -1) {
1647      pcs->Case = setting;
1648   } else {
1649      file.lpos += strlen(buffer);
1650      compile_error_skip(-/*Found “%s”, expecting “PRESERVE”, “TOUPPER”, or “TOLOWER”*/10,
1651                         buffer);
1652   }
1653}
1654
1655typedef enum {
1656    CS_NONE = -1,
1657    CS_CUSTOM,
1658    CS_EPSG,
1659    CS_ESRI,
1660    CS_EUR,
1661    CS_IJTSK,
1662    CS_JTSK,
1663    CS_LAT,
1664    CS_LOCAL,
1665    CS_LONG,
1666    CS_OSGB,
1667    CS_S_MERC,
1668    CS_UTM
1669} cs_class;
1670
1671static const sztok cs_tab[] = {
1672     {"CUSTOM", CS_CUSTOM},
1673     {"EPSG",   CS_EPSG},       /* EPSG:<number> */
1674     {"ESRI",   CS_ESRI},       /* ESRI:<number> */
1675     {"EUR",    CS_EUR},        /* EUR79Z30 */
1676     {"IJTSK",  CS_IJTSK},      /* IJTSK or IJTSK03 */
1677     {"JTSK",   CS_JTSK},       /* JTSK or JTSK03 */
1678     {"LAT",    CS_LAT},        /* LAT-LONG */
1679     {"LOCAL",  CS_LOCAL},
1680     {"LONG",   CS_LONG},       /* LONG-LAT */
1681     {"OSGB",   CS_OSGB},       /* OSGB:<H, N, O, S or T><A-Z except I> */
1682     {"S",      CS_S_MERC},     /* S-MERC */
1683     {"UTM",    CS_UTM},        /* UTM<zone><N or S or nothing> */
1684     {NULL,     CS_NONE}
1685};
1686
1687static void
1688cmd_cs(void)
1689{
1690   char * proj_str = NULL;
1691   int proj_str_len;
1692   cs_class cs;
1693   int cs_sub = INT_MIN;
1694   filepos fp;
1695   bool output = fFalse;
1696   enum { YES, NO, MAYBE } ok_for_output = YES;
1697   static bool had_cs = fFalse;
1698
1699   if (!had_cs) {
1700      had_cs = fTrue;
1701      if (first_fix_name) {
1702         compile_error_at(first_fix_filename, first_fix_line,
1703                          /*Station “%s” fixed before CS command first used*/442,
1704                          sprint_prefix(first_fix_name));
1705      }
1706   }
1707
1708   get_pos(&fp);
1709   /* Note get_token() only accepts letters - it'll stop at digits so "UTM12"
1710    * will give token "UTM". */
1711   get_token();
1712   if (strcmp(ucbuffer, "OUT") == 0) {
1713      output = fTrue;
1714      get_token();
1715   }
1716   cs = match_tok(cs_tab, TABSIZE(cs_tab));
1717   switch (cs) {
1718      case CS_NONE:
1719         break;
1720      case CS_CUSTOM:
1721         ok_for_output = MAYBE;
1722         read_string(&proj_str, &proj_str_len);
1723         cs_sub = 0;
1724         break;
1725      case CS_EPSG: case CS_ESRI:
1726         ok_for_output = MAYBE;
1727         if (ch == ':' && isdigit(nextch())) {
1728            unsigned n = read_uint();
1729            if (n < 1000000) {
1730               cs_sub = (int)n;
1731            }
1732         }
1733         break;
1734      case CS_EUR:
1735         if (isdigit(ch) &&
1736             read_uint() == 79 &&
1737             (ch == 'Z' || ch == 'z') &&
1738             isdigit(nextch()) &&
1739             read_uint() == 30) {
1740            cs_sub = 7930;
1741         }
1742         break;
1743      case CS_JTSK:
1744         ok_for_output = NO;
1745         /* FALLTHRU */
1746      case CS_IJTSK:
1747         if (ch == '0') {
1748            if (nextch() == '3') {
1749               nextch();
1750               cs_sub = 3;
1751            }
1752         } else {
1753            cs_sub = 0;
1754         }
1755         break;
1756      case CS_LAT: case CS_LONG:
1757         ok_for_output = NO;
1758         if (ch == '-') {
1759            nextch();
1760            get_token_no_blanks();
1761            cs_class cs2 = match_tok(cs_tab, TABSIZE(cs_tab));
1762            if ((cs ^ cs2) == (CS_LAT ^ CS_LONG)) {
1763                cs_sub = 0;
1764            }
1765         }
1766         break;
1767      case CS_LOCAL:
1768         cs_sub = 0;
1769         break;
1770      case CS_OSGB:
1771         if (ch == ':') {
1772            int uch1 = toupper(nextch());
1773            if (strchr("HNOST", uch1)) {
1774               int uch2 = toupper(nextch());
1775               if (uch2 >= 'A' && uch2 <= 'Z' && uch2 != 'I') {
1776                  int x, y;
1777                  nextch();
1778                  if (uch1 > 'I') --uch1;
1779                  uch1 -= 'A';
1780                  if (uch2 > 'I') --uch2;
1781                  uch2 -= 'A';
1782                  x = uch1 % 5;
1783                  y = uch1 / 5;
1784                  x = (x * 5) + uch2 % 5;
1785                  y = (y * 5) + uch2 / 5;
1786                  cs_sub = y * 25 + x;
1787               }
1788            }
1789         }
1790         break;
1791      case CS_S_MERC:
1792         if (ch == '-') {
1793            nextch();
1794            get_token_no_blanks();
1795            if (strcmp(ucbuffer, "MERC") == 0) {
1796               cs_sub = 0;
1797            }
1798         }
1799         break;
1800      case CS_UTM:
1801         if (isdigit(ch)) {
1802            unsigned n = read_uint();
1803            if (n >= 1 && n <= 60) {
1804               int uch = toupper(ch);
1805               cs_sub = (int)n;
1806               if (uch == 'S') {
1807                  nextch();
1808                  cs_sub = -cs_sub;
1809               } else if (uch == 'N') {
1810                  nextch();
1811               }
1812            }
1813         }
1814         break;
1815   }
1816   if (cs_sub == INT_MIN || isalnum(ch)) {
1817      set_pos(&fp);
1818      compile_error_skip(-/*Unknown coordinate system*/434);
1819      return;
1820   }
1821   /* Actually handle the cs */
1822   switch (cs) {
1823      case CS_NONE:
1824         break;
1825      case CS_CUSTOM:
1826         /* proj_str already set */
1827         break;
1828      case CS_EPSG:
1829         proj_str = osmalloc(32);
1830         sprintf(proj_str, "+init=epsg:%d +no_defs", cs_sub);
1831         break;
1832      case CS_ESRI:
1833         proj_str = osmalloc(32);
1834         sprintf(proj_str, "+init=esri:%d +no_defs", cs_sub);
1835         break;
1836      case CS_EUR:
1837         proj_str = osstrdup("+proj=utm +zone=30 +ellps=intl +towgs84=-86,-98,-119,0,0,0,0 +no_defs");
1838         break;
1839      case CS_IJTSK:
1840         if (cs_sub == 0)
1841            proj_str = osstrdup("+proj=krovak +ellps=bessel +towgs84=570.8285,85.6769,462.842,4.9984,1.5867,5.2611,3.5623 +no_defs");
1842         else
1843            proj_str = osstrdup("+proj=krovak +ellps=bessel +towgs84=485.021,169.465,483.839,7.786342,4.397554,4.102655,0 +no_defs");
1844         break;
1845      case CS_JTSK:
1846         if (cs_sub == 0)
1847            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");
1848         else
1849            proj_str = osstrdup("+proj=krovak +czech +ellps=bessel +towgs84=485.021,169.465,483.839,7.786342,4.397554,4.102655,0 +no_defs");
1850         break;
1851      case CS_LAT:
1852         /* FIXME: Requires PROJ >= 4.8.0 for +axis, and the SDs will be
1853          * misapplied, so we may want to swap ourselves.  Also, while
1854          * therion supports lat-long, I'm not totally convinced that it is
1855          * sensible to do so - people often say "lat-long", but probably
1856          * don't think that that's actually "Northing, Easting".  This
1857          * seems like it'll result in people accidentally getting X and Y
1858          * swapped in their fixed points...
1859          */
1860#if 0
1861         proj_str = osstrdup("+proj=longlat +ellps=WGS84 +datum=WGS84 +axis=neu +no_defs");
1862#endif
1863         break;
1864      case CS_LOCAL:
1865         /* FIXME: Is it useful to be able to explicitly specify this? */
1866         break;
1867      case CS_LONG:
1868         proj_str = osstrdup("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
1869         break;
1870      case CS_OSGB: {
1871         int x = 14 - (cs_sub % 25);
1872         int y = (cs_sub / 25) - 20;
1873         proj_str = osmalloc(160);
1874         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);
1875         break;
1876      }
1877      case CS_S_MERC:
1878         proj_str = osstrdup("+proj=merc +lat_ts=0 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +units=m +nadgrids=@null +no_defs");
1879         break;
1880      case CS_UTM:
1881         proj_str = osmalloc(74);
1882         if (cs_sub > 0) {
1883            sprintf(proj_str, "+proj=utm +ellps=WGS84 +datum=WGS84 +units=m +zone=%d +no_defs", cs_sub);
1884         } else {
1885            sprintf(proj_str, "+proj=utm +ellps=WGS84 +datum=WGS84 +units=m +zone=%d +south +no_defs", -cs_sub);
1886         }
1887         break;
1888   }
1889
1890   if (!proj_str) {
1891      /* printf("CS %d:%d\n", (int)cs, cs_sub); */
1892      set_pos(&fp);
1893      compile_error_skip(-/*Unknown coordinate system*/434);
1894      return;
1895   }
1896
1897   if (output) {
1898      if (ok_for_output == NO) {
1899         set_pos(&fp);
1900         compile_error_skip(-/*Coordinate system unsuitable for output*/435);
1901         return;
1902      }
1903
1904      /* If the output projection is already set, we still need to create the
1905       * projection object for a custom projection, so we can report errors.
1906       * But if the string is identical, we know it's valid.
1907       */
1908      if (!proj_out ||
1909          (ok_for_output == MAYBE && strcmp(proj_str, proj_str_out) != 0)) {
1910         projPJ pj = pj_init_plus(proj_str);
1911         if (!pj) {
1912            set_pos(&fp);
1913            compile_error_skip(-/*Invalid coordinate system: %s*/443,
1914                               pj_strerrno(pj_errno));
1915            return;
1916         }
1917         if (ok_for_output == MAYBE && pj_is_latlong(pj)) {
1918            compile_error_skip(-/*Coordinate system unsuitable for output*/435);
1919            return;
1920         }
1921         if (proj_out) {
1922            pj_free(pj);
1923            osfree(proj_str);
1924         } else {
1925            proj_out = pj;
1926            proj_str_out = proj_str;
1927         }
1928      }
1929   } else {
1930      projPJ pj;
1931      if (proj_str_out && strcmp(proj_str, proj_str_out) == 0) {
1932         /* Same as the current output projection. */
1933         pj = proj_out;
1934      } else {
1935         pj = pj_init_plus(proj_str);
1936         if (!pj) {
1937            set_pos(&fp);
1938            compile_error_skip(-/*Invalid coordinate system: %s*/443,
1939                               pj_strerrno(pj_errno));
1940            return;
1941         }
1942      }
1943
1944      /* Free proj if not used by parent, or as the output projection. */
1945      settings * p = pcs;
1946      if (p->proj && (!p->next || p->proj != p->next->proj))
1947         if (p->proj != proj_out)
1948            pj_free(p->proj);
1949      p->proj = pj;
1950   }
1951}
1952
1953static const sztok infer_tab[] = {
1954     { "EQUATES",       INFER_EQUATES },
1955     { "EXPORTS",       INFER_EXPORTS },
1956     { "PLUMBS",        INFER_PLUMBS },
1957#if 0 /* FIXME */
1958     { "SUBSURVEYS",    INFER_SUBSURVEYS },
1959#endif
1960     { NULL,            INFER_NULL }
1961};
1962
1963static const sztok onoff_tab[] = {
1964     { "OFF", 0 },
1965     { "ON",  1 },
1966     { NULL, -1 }
1967};
1968
1969static void
1970cmd_infer(void)
1971{
1972   infer_what setting;
1973   int on;
1974   get_token();
1975   setting = match_tok(infer_tab, TABSIZE(infer_tab));
1976   if (setting == INFER_NULL) {
1977      file.lpos += strlen(buffer);
1978      compile_error_skip(-/*Found “%s”, expecting “EQUATES”, “EXPORTS”, or “PLUMBS”*/31, buffer);
1979      return;
1980   }
1981   get_token();
1982   on = match_tok(onoff_tab, TABSIZE(onoff_tab));
1983   if (on == -1) {
1984      file.lpos += strlen(buffer);
1985      compile_error_skip(-/*Found “%s”, expecting “ON” or “OFF”*/32, buffer);
1986      return;
1987   }
1988
1989   if (on) {
1990      pcs->infer |= BIT(setting);
1991      if (setting == INFER_EXPORTS) fExportUsed = fTrue;
1992   } else {
1993      pcs->infer &= ~BIT(setting);
1994   }
1995}
1996
1997static void
1998cmd_truncate(void)
1999{
2000   unsigned int truncate_at = 0; /* default is no truncation */
2001   filepos fp;
2002
2003   get_pos(&fp);
2004
2005   get_token();
2006   if (strcmp(ucbuffer, "OFF") != 0) {
2007      if (*ucbuffer) set_pos(&fp);
2008      truncate_at = read_uint();
2009   }
2010   /* for backward compatibility, "*truncate 0" means "*truncate off" */
2011   pcs->Truncate = (truncate_at == 0) ? INT_MAX : truncate_at;
2012}
2013
2014static void
2015cmd_require(void)
2016{
2017   const unsigned int version[] = {COMMAVERSION};
2018   const unsigned int *ver = version;
2019   filepos fp;
2020
2021   skipblanks();
2022   get_pos(&fp);
2023   while (1) {
2024      int diff = *ver++ - read_uint();
2025      if (diff > 0) break;
2026      if (diff < 0) {
2027         size_t i, len;
2028         char *v;
2029         filepos fp_tmp;
2030
2031         /* find end of version number */
2032         while (isdigit(ch) || ch == '.') nextch();
2033         get_pos(&fp_tmp);
2034         len = (size_t)(fp_tmp.offset - fp.offset);
2035         v = osmalloc(len + 1);
2036         set_pos(&fp);
2037         for (i = 0; i < len; i++) {
2038            v[i] = ch;
2039            nextch();
2040         }
2041         v[i] = '\0';
2042         /* TRANSLATORS: Feel free to translate as "or newer" instead of "or
2043          * greater" if that gives a more natural translation.  It's
2044          * technically not quite right when there are parallel active release
2045          * series (e.g. Survex 1.0.40 was released *after* 1.2.0), but this
2046          * seems unlikely to confuse users.  "Survex" is the name of the
2047          * software, so should not be translated.
2048          *
2049          * Here "survey" is a "cave map" rather than list of questions - it should be
2050          * translated to the terminology that cavers using the language would use.
2051          */
2052         fatalerror_in_file(file.filename, file.line, /*Survex version %s or greater required to process this survey data.*/2, v);
2053      }
2054      if (ch != '.') break;
2055      nextch();
2056      if (!isdigit(ch) || ver == version + sizeof(version)) break;
2057   }
2058   /* skip rest of version number */
2059   while (isdigit(ch) || ch == '.') nextch();
2060}
2061
2062/* allocate new meta_data if need be */
2063void
2064copy_on_write_meta(settings *s)
2065{
2066   if (!s->meta || s->meta->ref_count != 0) {
2067       meta_data * meta_new = osnew(meta_data);
2068       if (!s->meta) {
2069           meta_new->days1 = meta_new->days2 = -1;
2070       } else {
2071           *meta_new = *(s->meta);
2072       }
2073       meta_new->ref_count = 0;
2074       s->meta = meta_new;
2075   }
2076}
2077
2078static void
2079cmd_date(void)
2080{
2081    int year, month, day;
2082    int days1, days2;
2083    bool implicit_range = fFalse;
2084
2085    read_date(&year, &month, &day);
2086    days1 = days_since_1900(year, month ? month : 1, day ? day : 1);
2087
2088    if (days1 > current_days_since_1900) {
2089        compile_warning(-/*Date is in the future!*/80);
2090    }
2091
2092    skipblanks();
2093    if (ch == '-') {
2094        nextch();
2095        read_date(&year, &month, &day);
2096    } else {
2097        if (month && day) {
2098            days2 = days1;
2099            goto read;
2100        }
2101        implicit_range = fTrue;
2102    }
2103
2104    if (month == 0) month = 12;
2105    if (day == 0) day = last_day(year, month);
2106    days2 = days_since_1900(year, month, day);
2107
2108    if (!implicit_range && days2 > current_days_since_1900) {
2109        compile_warning(-/*Date is in the future!*/80);
2110    }
2111
2112    if (days2 < days1) {
2113        compile_error(-/*End of date range is before the start*/81);
2114    }
2115
2116read:
2117    copy_on_write_meta(pcs);
2118    pcs->meta->days1 = days1;
2119    pcs->meta->days2 = days2;
2120}
2121
2122typedef void (*cmd_fn)(void);
2123
2124static const cmd_fn cmd_funcs[] = {
2125   cmd_alias,
2126   cmd_begin,
2127   cmd_calibrate,
2128   cmd_case,
2129   skipline, /*cmd_copyright,*/
2130   cmd_cs,
2131   cmd_data,
2132   cmd_date,
2133#ifndef NO_DEPRECATED
2134   cmd_default,
2135#endif
2136   cmd_end,
2137   cmd_entrance,
2138   cmd_equate,
2139   cmd_export,
2140   cmd_fix,
2141   cmd_flags,
2142   cmd_include,
2143   cmd_infer,
2144   skipline, /*cmd_instrument,*/
2145#ifndef NO_DEPRECATED
2146   cmd_prefix,
2147#endif
2148   cmd_require,
2149   cmd_sd,
2150   cmd_set,
2151   solve_network,
2152   skipline, /*cmd_team,*/
2153   cmd_title,
2154   cmd_truncate,
2155   cmd_units
2156};
2157
2158extern void
2159handle_command(void)
2160{
2161   int cmdtok;
2162   get_token();
2163   cmdtok = match_tok(cmd_tab, TABSIZE(cmd_tab));
2164
2165   if (cmdtok < 0 || cmdtok >= (int)(sizeof(cmd_funcs) / sizeof(cmd_fn))) {
2166      file.lpos += strlen(buffer);
2167      compile_error_skip(-/*Unknown command “%s”*/12, buffer);
2168      return;
2169   }
2170
2171   switch (cmdtok) {
2172    case CMD_EXPORT:
2173      if (!f_export_ok)
2174         /* TRANSLATORS: The *EXPORT command is only valid just after *BEGIN
2175          * <SURVEY>, so this would generate this error:
2176          *
2177          * *begin fred
2178          * 1 2 1.23 045 -6
2179          * *export 2
2180          * *end fred */
2181         compile_error(/**EXPORT must immediately follow “*BEGIN <SURVEY>”*/57);
2182      break;
2183    case CMD_COPYRIGHT:
2184    case CMD_DATE:
2185    case CMD_INSTRUMENT:
2186    case CMD_TEAM:
2187    case CMD_TITLE:
2188      /* These can occur between *begin and *export */
2189      break;
2190    default:
2191      /* NB: additional handling for "*begin <survey>" in cmd_begin */
2192      f_export_ok = fFalse;
2193      break;
2194   }
2195
2196   cmd_funcs[cmdtok]();
2197}
Note: See TracBrowser for help on using the repository browser.