source: git/src/commands.c @ 0b8c321

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

lib/survex.pot,src/: Add more TRANSLATOR comments.

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