source: git/src/commands.c @ 53496ab3

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 53496ab3 was 200a12c, checked in by Olly Betts <olly@…>, 11 years ago

src/commands.c: Fix ordering of the style masks to reflect swapping
of STYLE_NOSURVEY and STYLE_PASSAGE.

  • Property mode set to 100644
File size: 44.1 KB
Line 
1/* commands.c
2 * Code for directives
3 * Copyright (C) 1991-2003,2004,2005,2006,2010,2011,2012,2013 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 "cavern.h"
29#include "commands.h"
30#include "datain.h"
31#include "date.h"
32#include "debug.h"
33#include "filename.h"
34#include "message.h"
35#include "netbits.h"
36#include "netskel.h"
37#include "out.h"
38#include "readval.h"
39#include "str.h"
40
41static void
42default_grade(settings *s)
43{
44   /* Values correspond to those in bcra5.svx */
45   s->Var[Q_POS] = (real)sqrd(0.05);
46   s->Var[Q_LENGTH] = (real)sqrd(0.05);
47   s->Var[Q_COUNT] = (real)sqrd(0.05);
48   s->Var[Q_DX] = s->Var[Q_DY] = s->Var[Q_DZ] = (real)sqrd(0.05);
49   s->Var[Q_BEARING] = (real)sqrd(rad(0.5));
50   s->Var[Q_GRADIENT] = (real)sqrd(rad(0.5));
51   s->Var[Q_BACKBEARING] = (real)sqrd(rad(0.5));
52   s->Var[Q_BACKGRADIENT] = (real)sqrd(rad(0.5));
53   /* SD of plumbed legs (0.25 degrees?) */
54   s->Var[Q_PLUMB] = (real)sqrd(rad(0.25));
55   /* SD of level legs (0.25 degrees?) */
56   s->Var[Q_LEVEL] = (real)sqrd(rad(0.25));
57   s->Var[Q_DEPTH] = (real)sqrd(0.05);
58}
59
60static void
61default_truncate(settings *s)
62{
63   s->Truncate = INT_MAX;
64}
65
66static void
67default_case(settings *s)
68{
69   s->Case = LOWER;
70}
71
72static reading default_order[] = { Fr, To, Tape, Comp, Clino, End };
73
74static void
75default_style(settings *s)
76{
77   s->style = STYLE_NORMAL;
78   s->ordering = default_order;
79   s->dash_for_anon_wall_station = fFalse;
80}
81
82static void
83default_prefix(settings *s)
84{
85   s->Prefix = root;
86}
87
88static void
89default_translate(settings *s)
90{
91   int i;
92   short *t;
93   if (s->next && s->next->Translate == s->Translate) {
94      t = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
95      memcpy(t - 1, s->Translate - 1, sizeof(short) * 257);
96      s->Translate = t;
97   }
98/*  SVX_ASSERT(EOF==-1);*/ /* important, since we rely on this */
99   t = s->Translate;
100   memset(t - 1, 0, sizeof(short) * 257);
101   for (i = '0'; i <= '9'; i++) t[i] = SPECIAL_NAMES;
102   for (i = 'A'; i <= 'Z'; i++) t[i] = SPECIAL_NAMES;
103   for (i = 'a'; i <= 'z'; i++) t[i] = SPECIAL_NAMES;
104
105   t['\t'] |= SPECIAL_BLANK;
106   t[' '] |= SPECIAL_BLANK;
107   t[','] |= SPECIAL_BLANK;
108   t[';'] |= SPECIAL_COMMENT;
109   t['\032'] |= SPECIAL_EOL; /* Ctrl-Z, so olde DOS text files are handled ok */
110   t[EOF] |= SPECIAL_EOL;
111   t['\n'] |= SPECIAL_EOL;
112   t['\r'] |= SPECIAL_EOL;
113   t['*'] |= SPECIAL_KEYWORD;
114   t['-'] |= SPECIAL_OMIT;
115   t['\\'] |= SPECIAL_ROOT;
116   t['.'] |= SPECIAL_SEPARATOR;
117   t['_'] |= SPECIAL_NAMES;
118   t['-'] |= SPECIAL_NAMES; /* Added in 0.97 prerelease 4 */
119   t['.'] |= SPECIAL_DECIMAL;
120   t['-'] |= SPECIAL_MINUS;
121   t['+'] |= SPECIAL_PLUS;
122#if 0 /* FIXME */
123   t['{'] |= SPECIAL_OPEN;
124   t['}'] |= SPECIAL_CLOSE;
125#endif
126}
127
128void
129default_units(settings *s)
130{
131   int quantity;
132   for (quantity = 0; quantity < Q_MAC; quantity++) {
133      if (TSTBIT(ANG_QMASK, quantity))
134         s->units[quantity] = (real)(M_PI / 180.0); /* degrees */
135      else
136         s->units[quantity] = (real)1.0; /* metres */
137   }
138   s->f_clino_percent = s->f_backclino_percent = fFalse;
139}
140
141void
142default_calib(settings *s)
143{
144   int quantity;
145   for (quantity = 0; quantity < Q_MAC; quantity++) {
146      s->z[quantity] = (real)0.0;
147      s->sc[quantity] = (real)1.0;
148   }
149}
150
151static void
152default_flags(settings *s)
153{
154   s->flags = 0;
155}
156
157extern void
158default_all(settings *s)
159{
160   default_truncate(s);
161   s->infer = 0;
162   default_case(s);
163   default_style(s);
164   default_prefix(s);
165   default_translate(s);
166   default_grade(s);
167   default_units(s);
168   default_calib(s);
169   default_flags(s);
170}
171
172char *buffer = NULL;
173static int buf_len;
174
175static char *ucbuffer = NULL;
176
177/* read token */
178extern void
179get_token(void)
180{
181   int i = -1;
182
183   s_zero(&buffer);
184   osfree(ucbuffer);
185   skipblanks();
186   while (isalpha(ch)) {
187      s_catchar(&buffer, &buf_len, (char)ch);
188      nextch();
189   }
190
191   if (!buffer) s_catchar(&buffer, &buf_len, '\0');
192
193   ucbuffer = osmalloc(buf_len);
194   do {
195      i++;
196      ucbuffer[i] = toupper(buffer[i]);
197   } while (buffer[i]);
198#if 0
199   printf("get_token() got “%s”\n", buffer);
200#endif
201}
202
203/* read word */
204static void
205get_word(void)
206{
207   s_zero(&buffer);
208   skipblanks();
209   while (!isBlank(ch) && !isEol(ch)) {
210      s_catchar(&buffer, &buf_len, (char)ch);
211      nextch();
212   }
213
214   if (!buffer) s_catchar(&buffer, &buf_len, '\0');
215#if 0
216   printf("get_word() got “%s”\n", buffer);
217#endif
218}
219
220/* match_tok() now uses binary chop
221 * tab argument should be alphabetically sorted (ascending)
222 */
223extern int
224match_tok(const sztok *tab, int tab_size)
225{
226   int a = 0, b = tab_size - 1, c;
227   int r;
228   assert(tab_size > 0); /* catch empty table */
229/*  printf("[%d,%d]",a,b); */
230   while (a <= b) {
231      c = (unsigned)(a + b) / 2;
232/*     printf(" %d",c); */
233      r = strcmp(tab[c].sz, ucbuffer);
234      if (r == 0) return tab[c].tok; /* match */
235      if (r < 0)
236         a = c + 1;
237      else
238         b = c - 1;
239   }
240   return tab[tab_size].tok; /* no match */
241}
242
243typedef enum {
244   CMD_NULL = -1, CMD_ALIAS, CMD_BEGIN, CMD_CALIBRATE, CMD_CASE, CMD_COPYRIGHT,
245   CMD_DATA, CMD_DATE, CMD_DEFAULT, CMD_END, CMD_ENTRANCE, CMD_EQUATE,
246   CMD_EXPORT, CMD_FIX, CMD_FLAGS, CMD_INCLUDE, CMD_INFER, CMD_INSTRUMENT,
247   CMD_PREFIX, CMD_REQUIRE, CMD_SD, CMD_SET, CMD_SOLVE,
248   CMD_TEAM, CMD_TITLE, CMD_TRUNCATE, CMD_UNITS
249} cmds;
250
251static sztok cmd_tab[] = {
252     {"ALIAS",     CMD_ALIAS},
253     {"BEGIN",     CMD_BEGIN},
254     {"CALIBRATE", CMD_CALIBRATE},
255     {"CASE",      CMD_CASE},
256     {"COPYRIGHT", CMD_COPYRIGHT},
257     {"DATA",      CMD_DATA},
258     {"DATE",      CMD_DATE},
259#ifndef NO_DEPRECATED
260     {"DEFAULT",   CMD_DEFAULT},
261#endif
262     {"END",       CMD_END},
263     {"ENTRANCE",  CMD_ENTRANCE},
264     {"EQUATE",    CMD_EQUATE},
265     {"EXPORT",    CMD_EXPORT},
266     {"FIX",       CMD_FIX},
267     {"FLAGS",     CMD_FLAGS},
268     {"INCLUDE",   CMD_INCLUDE},
269     {"INFER",     CMD_INFER},
270     {"INSTRUMENT",CMD_INSTRUMENT},
271#ifndef NO_DEPRECATED
272     {"PREFIX",    CMD_PREFIX},
273#endif
274     {"REQUIRE",   CMD_REQUIRE},
275     {"SD",        CMD_SD},
276     {"SET",       CMD_SET},
277     {"SOLVE",     CMD_SOLVE},
278     {"TEAM",      CMD_TEAM},
279     {"TITLE",     CMD_TITLE},
280     {"TRUNCATE",  CMD_TRUNCATE},
281     {"UNITS",     CMD_UNITS},
282     {NULL,        CMD_NULL}
283};
284
285/* masks for units which are length and angles respectively */
286#define LEN_UMASK (BIT(UNITS_METRES) | BIT(UNITS_FEET) | BIT(UNITS_YARDS))
287#define ANG_UMASK (BIT(UNITS_DEGS) | BIT(UNITS_GRADS) | BIT(UNITS_MINUTES))
288
289/* ordering must be the same as the units enum */
290static real factor_tab[] = {
291   1.0, METRES_PER_FOOT, (METRES_PER_FOOT*3.0),
292   (M_PI/180.0), (M_PI/200.0), 0.01, (M_PI/180.0/60.0)
293};
294
295static int
296get_units(unsigned long qmask, bool percent_ok)
297{
298   static sztok utab[] = {
299        {"DEGREES",       UNITS_DEGS },
300        {"DEGS",          UNITS_DEGS },
301        {"FEET",          UNITS_FEET },
302        {"GRADS",         UNITS_GRADS },
303        {"METERS",        UNITS_METRES },
304        {"METRES",        UNITS_METRES },
305        {"METRIC",        UNITS_METRES },
306        {"MILS",          UNITS_GRADS },
307        {"MINUTES",       UNITS_MINUTES },
308        {"PERCENT",       UNITS_PERCENT },
309        {"PERCENTAGE",    UNITS_PERCENT },
310        {"YARDS",         UNITS_YARDS },
311        {NULL,            UNITS_NULL }
312   };
313   int units;
314   get_token();
315   units = match_tok(utab, TABSIZE(utab));
316   if (units == UNITS_NULL) {
317      file.lpos += strlen(buffer);
318      compile_error_skip(-/*Unknown units “%s”*/35, buffer);
319      return UNITS_NULL;
320   }
321   if (units == UNITS_PERCENT && percent_ok &&
322       !(qmask & ~(BIT(Q_GRADIENT)|BIT(Q_BACKGRADIENT)))) {
323      return units;
324   }
325   if (((qmask & LEN_QMASK) && !TSTBIT(LEN_UMASK, units)) ||
326       ((qmask & ANG_QMASK) && !TSTBIT(ANG_UMASK, units))) {
327      file.lpos += strlen(buffer);
328      compile_error_skip(-/*Invalid units “%s” for quantity*/37, buffer);
329      return UNITS_NULL;
330   }
331   return units;
332}
333
334/* returns mask with bit x set to indicate quantity x specified */
335static unsigned long
336get_qlist(unsigned long mask_bad)
337{
338   static sztok qtab[] = {
339        {"ALTITUDE",     Q_DZ },
340        {"BACKBEARING",  Q_BACKBEARING },
341        {"BACKCLINO",    Q_BACKGRADIENT },    /* alternative name */
342        {"BACKCOMPASS",  Q_BACKBEARING },     /* alternative name */
343        {"BACKGRADIENT", Q_BACKGRADIENT },
344        {"BEARING",      Q_BEARING },
345        {"CEILING",      Q_UP },          /* alternative name */
346        {"CLINO",        Q_GRADIENT },    /* alternative name */
347        {"COMPASS",      Q_BEARING },     /* alternative name */
348        {"COUNT",        Q_COUNT },
349        {"COUNTER",      Q_COUNT },       /* alternative name */
350        {"DECLINATION",  Q_DECLINATION },
351        {"DEFAULT",      Q_DEFAULT }, /* not a real quantity... */
352        {"DEPTH",        Q_DEPTH },
353        {"DOWN",         Q_DOWN },
354        {"DX",           Q_DX },          /* alternative name */
355        {"DY",           Q_DY },          /* alternative name */
356        {"DZ",           Q_DZ },          /* alternative name */
357        {"EASTING",      Q_DX },
358        {"FLOOR",        Q_DOWN },        /* alternative name */
359        {"GRADIENT",     Q_GRADIENT },
360        {"LEFT",         Q_LEFT },
361        {"LENGTH",       Q_LENGTH },
362        {"LEVEL",        Q_LEVEL},
363        {"NORTHING",     Q_DY },
364        {"PLUMB",        Q_PLUMB},
365        {"POSITION",     Q_POS },
366        {"RIGHT",        Q_RIGHT },
367        {"TAPE",         Q_LENGTH },      /* alternative name */
368        {"UP",           Q_UP },
369        {NULL,           Q_NULL }
370   };
371   unsigned long qmask = 0;
372   int tok;
373   filepos fp;
374
375   while (1) {
376      get_pos(&fp);
377      get_token();
378      tok = match_tok(qtab, TABSIZE(qtab));
379      if (tok == Q_DEFAULT && !(mask_bad & BIT(Q_DEFAULT))) {
380          /* Only recognise DEFAULT if it is the first quantity, and then don't
381           * look for any more. */
382          if (qmask == 0)
383              return BIT(Q_DEFAULT);
384          break;
385      }
386      /* bail out if we reach the table end with no match */
387      if (tok == Q_NULL) break;
388      qmask |= BIT(tok);
389      if (qmask & mask_bad) {
390         file.lpos += strlen(buffer);
391         compile_error_skip(-/*Unknown instrument “%s”*/39, buffer);
392         return 0;
393      }
394   }
395
396   if (qmask == 0) {
397      file.lpos += strlen(buffer);
398      compile_error_skip(-/*Unknown quantity “%s”*/34, buffer);
399   } else {
400      set_pos(&fp);
401   }
402
403   return qmask;
404}
405
406#define SPECIAL_UNKNOWN 0
407static void
408cmd_set(void)
409{
410   static sztok chartab[] = {
411        {"BLANK",     SPECIAL_BLANK },
412/*FIXME {"CLOSE",     SPECIAL_CLOSE }, */
413        {"COMMENT",   SPECIAL_COMMENT },
414        {"DECIMAL",   SPECIAL_DECIMAL },
415        {"EOL",       SPECIAL_EOL }, /* EOL won't work well */
416        {"KEYWORD",   SPECIAL_KEYWORD },
417        {"MINUS",     SPECIAL_MINUS },
418        {"NAMES",     SPECIAL_NAMES },
419        {"OMIT",      SPECIAL_OMIT },
420/*FIXME {"OPEN",      SPECIAL_OPEN }, */
421        {"PLUS",      SPECIAL_PLUS },
422#ifndef NO_DEPRECATED
423        {"ROOT",      SPECIAL_ROOT },
424#endif
425        {"SEPARATOR", SPECIAL_SEPARATOR },
426        {NULL,        SPECIAL_UNKNOWN }
427   };
428   int mask;
429   int i;
430
431   get_token();
432   mask = match_tok(chartab, TABSIZE(chartab));
433
434   if (mask == SPECIAL_UNKNOWN) {
435      file.lpos += strlen(buffer);
436      compile_error_skip(-/*Unknown character class “%s”*/42, buffer);
437      return;
438   }
439
440#ifndef NO_DEPRECATED
441   if (mask == SPECIAL_ROOT) {
442      if (root_depr_count < 5) {
443         file.lpos += strlen(buffer);
444         compile_warning(-/*ROOT is deprecated*/25);
445         if (++root_depr_count == 5)
446            compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
447      }
448   }
449#endif
450
451   /* if we're currently using an inherited translation table, allocate a new
452    * table, and copy old one into it */
453   if (pcs->next && pcs->next->Translate == pcs->Translate) {
454      short *p;
455      p = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
456      memcpy(p - 1, pcs->Translate - 1, sizeof(short) * 257);
457      pcs->Translate = p;
458   }
459
460   skipblanks();
461
462   /* clear this flag for all non-alphanums */
463   for (i = 0; i < 256; i++)
464      if (!isalnum(i)) pcs->Translate[i] &= ~mask;
465
466   /* now set this flag for all specified chars */
467   while (!isEol(ch)) {
468      if (!isalnum(ch)) {
469         pcs->Translate[ch] |= mask;
470      } else if (tolower(ch) == 'x') {
471         int hex;
472         filepos fp;
473         get_pos(&fp);
474         nextch();
475         if (!isxdigit(ch)) {
476            set_pos(&fp);
477            break;
478         }
479         hex = isdigit(ch) ? ch - '0' : tolower(ch) - 'a';
480         nextch();
481         if (!isxdigit(ch)) {
482            set_pos(&fp);
483            break;
484         }
485         hex = hex << 4 | (isdigit(ch) ? ch - '0' : tolower(ch) - 'a');
486         pcs->Translate[hex] |= mask;
487      } else {
488         break;
489      }
490      nextch();
491   }
492}
493
494static void
495check_reentry(prefix *tag)
496{
497   /* Don't try to check "*prefix \" or "*begin \" */
498   if (!tag->up) return;
499   if (TSTBIT(tag->sflags, SFLAGS_PREFIX_ENTERED)) {
500      if (tag->line != file.line ||
501          strcmp(tag->filename, file.filename) != 0) {
502         const char *filename_store = file.filename;
503         unsigned int line_store = file.line;
504         static int reenter_depr_count = 0;
505
506         if (reenter_depr_count < 5) {
507            compile_warning(/*Reentering an existing prefix level is deprecated*/29);
508            if (++reenter_depr_count == 5)
509               compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
510         }
511
512         file.filename = tag->filename;
513         file.line = tag->line;
514         compile_warning(/*Originally entered here*/30);
515         file.filename = filename_store;
516         file.line = line_store;
517      }
518   } else {
519      tag->sflags |= BIT(SFLAGS_PREFIX_ENTERED);
520      tag->filename = file.filename;
521      tag->line = file.line;
522   }
523}
524
525#ifndef NO_DEPRECATED
526static void
527cmd_prefix(void)
528{
529   static int prefix_depr_count = 0;
530   prefix *tag;
531   /* Issue warning first, so "*prefix \" warns first that *prefix is
532    * deprecated and then that ROOT is...
533    */
534   if (prefix_depr_count < 5) {
535      compile_warning(-/**prefix is deprecated - use *begin and *end instead*/6);
536      if (++prefix_depr_count == 5)
537         compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
538   }
539   tag = read_prefix(PFX_SURVEY|PFX_ALLOW_ROOT);
540   pcs->Prefix = tag;
541   check_reentry(tag);
542}
543#endif
544
545static void
546cmd_alias(void)
547{
548   /* Currently only two forms are supported:
549    * *alias station - ..
550    * *alias station -
551    */
552   get_token();
553   if (strcmp(ucbuffer, "STATION") != 0)
554      goto bad;
555   get_word();
556   if (strcmp(buffer, "-") != 0)
557      goto bad;
558   get_word();
559   if (*buffer && strcmp(buffer, "..") != 0)
560      goto bad;
561   pcs->dash_for_anon_wall_station = (*buffer != '\0');
562   return;
563bad:
564   compile_error_skip(/*Bad *alias command*/397);
565}
566
567static void
568cmd_begin(void)
569{
570   prefix *tag;
571   settings *pcsNew;
572
573   pcsNew = osnew(settings);
574   *pcsNew = *pcs; /* copy contents */
575   pcsNew->begin_lineno = file.line;
576   pcsNew->next = pcs;
577   pcs = pcsNew;
578
579   tag = read_prefix(PFX_SURVEY|PFX_OPT|PFX_ALLOW_ROOT|PFX_WARN_SEPARATOR);
580   pcs->tag = tag;
581   if (tag) {
582      pcs->Prefix = tag;
583      check_reentry(tag);
584      f_export_ok = fTrue;
585   }
586}
587
588extern void
589free_settings(settings *p) {
590   /* don't free default ordering or ordering used by parent */
591   reading *order = p->ordering;
592   if (order != default_order && (!p->next || order != p->next->ordering))
593      osfree(order);
594
595   /* free Translate if not used by parent */
596   if (!p->next || p->Translate != p->next->Translate)
597      osfree(p->Translate - 1);
598
599   /* free meta is not used by parent, or in this block */
600   if (p->meta && p->meta != p->next->meta && p->meta->ref_count == 0)
601       osfree(p->meta);
602
603   osfree(p);
604}
605
606static void
607cmd_end(void)
608{
609   settings *pcsParent;
610   prefix *tag, *tagBegin;
611
612   pcsParent = pcs->next;
613
614   if (pcs->begin_lineno == 0) {
615      if (pcsParent == NULL) {
616         /* more ENDs than BEGINs */
617         compile_error_skip(/*No matching BEGIN*/192);
618      } else {
619         compile_error_skip(/*END with no matching BEGIN in this file*/22);
620      }
621      return;
622   }
623
624   tagBegin = pcs->tag;
625
626   SVX_ASSERT(pcsParent);
627   free_settings(pcs);
628   pcs = pcsParent;
629
630   /* note need to read using root *before* BEGIN */
631   tag = read_prefix(PFX_SURVEY|PFX_OPT|PFX_ALLOW_ROOT);
632   if (tag != tagBegin) {
633      if (tag) {
634         if (!tagBegin) {
635            /* "*begin" / "*end foo" */
636            compile_error_skip(-/*Matching BEGIN tag has no prefix*/36);
637         } else {
638            /* tag mismatch */
639            compile_error_skip(-/*Prefix tag doesn’t match BEGIN*/193);
640         }
641      } else {
642         /* close tag omitted; open tag given */
643         compile_warning(-/*Closing prefix omitted from END*/194);
644      }
645   }
646}
647
648static void
649cmd_entrance(void)
650{
651   prefix *pfx = read_prefix(PFX_STATION);
652   pfx->sflags |= BIT(SFLAGS_ENTRANCE);
653}
654
655static void
656cmd_fix(void)
657{
658   prefix *fix_name;
659   node *stn = NULL;
660   static node *stnOmitAlready = NULL;
661   real x, y, z;
662   int nx, ny, nz;
663   filepos fp;
664
665   fix_name = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
666   fix_name->sflags |= BIT(SFLAGS_FIXED);
667
668   get_pos(&fp);
669   get_token();
670   if (strcmp(ucbuffer, "REFERENCE") == 0) {
671      /* suppress "unused fixed point" warnings for this station */
672      fix_name->sflags |= BIT(SFLAGS_USED);
673   } else {
674      if (*ucbuffer) set_pos(&fp);
675   }
676
677   x = read_numeric(fTrue, &nx);
678   if (x == HUGE_REAL) {
679      /* If the end of the line isn't blank, read a number after all to
680       * get a more helpful error message */
681      if (!isEol(ch) && !isComm(ch)) x = read_numeric(fFalse, &nx);
682   }
683   if (x == HUGE_REAL) {
684      if (stnOmitAlready) {
685         if (fix_name != stnOmitAlready->name) {
686            compile_error_skip(/*More than one FIX command with no coordinates*/56);
687         } else {
688            compile_warning(/*Same station fixed twice with no coordinates*/61);
689         }
690         return;
691      }
692      stn = StnFromPfx(fix_name);
693      compile_warning(/*FIX command with no coordinates - fixing at (0,0,0)*/54);
694      x = y = z = (real)0.0;
695      stnOmitAlready = stn;
696   } else {
697      real sdx;
698      y = read_numeric(fFalse, &ny);
699      z = read_numeric(fFalse, &nz);
700      sdx = read_numeric(fTrue, NULL);
701      if (sdx != HUGE_REAL) {
702         real sdy, sdz;
703         real cxy = 0, cyz = 0, czx = 0;
704         sdy = read_numeric(fTrue, NULL);
705         if (sdy == HUGE_REAL) {
706            /* only one variance given */
707            sdy = sdz = sdx;
708         } else {
709            sdz = read_numeric(fTrue, NULL);
710            if (sdz == HUGE_REAL) {
711               /* two variances given - horizontal & vertical */
712               sdz = sdy;
713               sdy = sdx;
714            } else {
715               cxy = read_numeric(fTrue, NULL);
716               if (cxy != HUGE_REAL) {
717                  /* covariances given */
718                  cyz = read_numeric(fFalse, NULL);
719                  czx = read_numeric(fFalse, NULL);
720               } else {
721                  cxy = 0;
722               }
723            }
724         }
725         stn = StnFromPfx(fix_name);
726         if (!fixed(stn)) {
727            node *fixpt = osnew(node);
728            prefix *name;
729            name = osnew(prefix);
730            name->pos = osnew(pos);
731            name->ident = NULL;
732            name->shape = 0;
733            fixpt->name = name;
734            name->stn = fixpt;
735            name->up = NULL;
736            if (TSTBIT(pcs->infer, INFER_EXPORTS)) {
737               name->min_export = USHRT_MAX;
738            } else {
739               name->min_export = 0;
740            }
741            name->max_export = 0;
742            name->sflags = 0;
743            add_stn_to_list(&stnlist, fixpt);
744            POS(fixpt, 0) = x;
745            POS(fixpt, 1) = y;
746            POS(fixpt, 2) = z;
747            fix(fixpt);
748            fixpt->leg[0] = fixpt->leg[1] = fixpt->leg[2] = NULL;
749            addfakeleg(fixpt, stn, 0, 0, 0,
750                       sdx * sdx, sdy * sdy, sdz * sdz
751#ifndef NO_COVARIANCES
752                       , cxy, cyz, czx
753#endif
754                       );
755         }
756         return;
757      }
758      stn = StnFromPfx(fix_name);
759   }
760
761   if (!fixed(stn)) {
762      POS(stn, 0) = x;
763      POS(stn, 1) = y;
764      POS(stn, 2) = z;
765      fix(stn);
766      return;
767   }
768
769   if (x != POS(stn, 0) || y != POS(stn, 1) || z != POS(stn, 2)) {
770      compile_error(/*Station already fixed or equated to a fixed point*/46);
771      return;
772   }
773   compile_warning(/*Station already fixed at the same coordinates*/55);
774}
775
776static void
777cmd_flags(void)
778{
779   static sztok flagtab[] = {
780        {"DUPLICATE", FLAGS_DUPLICATE },
781        {"NOT",       FLAGS_NOT },
782        {"SPLAY",     FLAGS_SPLAY },
783        {"SURFACE",   FLAGS_SURFACE },
784        {NULL,        FLAGS_UNKNOWN }
785   };
786   bool fNot = fFalse;
787   bool fEmpty = fTrue;
788   while (1) {
789      int flag;
790      get_token();
791      /* If buffer is empty, it could mean end of line, or maybe
792       * some non-letter junk which is better reported later */
793      if (!buffer[0]) break;
794
795      fEmpty = fFalse;
796      flag = match_tok(flagtab, TABSIZE(flagtab));
797      /* treat the second NOT in "NOT NOT" as an unknown flag */
798      if (flag == FLAGS_UNKNOWN || (fNot && flag == FLAGS_NOT)) {
799         file.lpos += strlen(buffer);
800         compile_error(-/*FLAG “%s” unknown*/68, buffer);
801         /* Recover from “*FLAGS NOT BOGUS SURFACE” by ignoring "NOT BOGUS" */
802         fNot = fFalse;
803      } else if (flag == FLAGS_NOT) {
804         fNot = fTrue;
805      } else if (fNot) {
806         pcs->flags &= ~BIT(flag);
807         fNot = fFalse;
808      } else {
809         pcs->flags |= BIT(flag);
810      }
811   }
812
813   if (fNot) {
814      file.lpos += strlen(buffer);
815      compile_error(-/*Expecting “DUPLICATE”, “SPLAY”, or “SURFACE”*/188);
816   } else if (fEmpty) {
817      file.lpos += strlen(buffer);
818      compile_error(-/*Expecting “NOT”, “DUPLICATE”, “SPLAY”, or “SURFACE”*/189);
819   }
820}
821
822static void
823cmd_equate(void)
824{
825   prefix *name1, *name2;
826   bool fOnlyOneStn = fTrue; /* to trap eg *equate entrance.6 */
827
828   name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO);
829   while (fTrue) {
830      name2 = name1;
831      name1 = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_SUSPECT_TYPO|PFX_OPT);
832      if (name1 == NULL) {
833         if (fOnlyOneStn) {
834            compile_error_skip(-/*Only one station in EQUATE command*/33);
835         }
836         return;
837      }
838
839      process_equate(name1, name2);
840      fOnlyOneStn = fFalse;
841   }
842}
843
844static void
845report_missing_export(prefix *pfx, int depth)
846{
847   const char *filename_store = file.filename;
848   unsigned int line_store = file.line;
849   prefix *survey = pfx;
850   char *s;
851   int i;
852   for (i = depth + 1; i; i--) {
853      survey = survey->up;
854      SVX_ASSERT(survey);
855   }
856   s = osstrdup(sprint_prefix(survey));
857   if (survey->filename) {
858      file.filename = survey->filename;
859      file.line = survey->line;
860   }
861   compile_error(/*Station “%s” not exported from survey “%s”*/26,
862                 sprint_prefix(pfx), s);
863   if (survey->filename) {
864      file.filename = filename_store;
865      file.line = line_store;
866   }
867   osfree(s);
868}
869
870static void
871cmd_export(void)
872{
873   prefix *pfx;
874
875   fExportUsed = fTrue;
876   pfx = read_prefix(PFX_STATION);
877   do {
878      int depth = 0;
879      {
880         prefix *p = pfx;
881         while (p != NULL && p != pcs->Prefix) {
882            depth++;
883            p = p->up;
884         }
885         /* Something like: *export \foo, but we've excluded use of root */
886         SVX_ASSERT(p);
887      }
888      /* *export \ or similar bogus stuff */
889      SVX_ASSERT(depth);
890#if 0
891      printf("C min %d max %d depth %d pfx %s\n",
892             pfx->min_export, pfx->max_export, depth, sprint_prefix(pfx));
893#endif
894      if (pfx->min_export == 0) {
895         /* not encountered *export for this name before */
896         if (pfx->max_export > depth) report_missing_export(pfx, depth);
897         pfx->min_export = pfx->max_export = depth;
898      } else if (pfx->min_export != USHRT_MAX) {
899         /* FIXME: what to do if a station is marked for inferred exports
900          * but is then explicitly exported?  Currently we just ignore the
901          * explicit export... */
902         if (pfx->min_export - 1 > depth) {
903            report_missing_export(pfx, depth);
904         } else if (pfx->min_export - 1 < depth) {
905            compile_error(/*Station “%s” already exported*/66,
906                          sprint_prefix(pfx));
907         }
908         pfx->min_export = depth;
909      }
910      pfx = read_prefix(PFX_STATION|PFX_OPT);
911   } while (pfx);
912}
913
914static void
915cmd_data(void)
916{
917   static sztok dtab[] = {
918        {"ALTITUDE",     Dz },
919        {"BACKBEARING",  BackComp },
920        {"BACKCLINO",    BackClino }, /* alternative name */
921        {"BACKCOMPASS",  BackComp }, /* alternative name */
922        {"BACKGRADIENT", BackClino },
923        {"BEARING",      Comp },
924        {"CEILING",      Up }, /* alternative name */
925        {"CLINO",        Clino }, /* alternative name */
926        {"COMPASS",      Comp }, /* alternative name */
927        {"COUNT",        Count }, /* FrCount&ToCount in multiline */
928        {"DEPTH",        Depth }, /* FrDepth&ToDepth in multiline */
929        {"DEPTHCHANGE",  DepthChange },
930        {"DIRECTION",    Dir },
931        {"DOWN",         Down },
932        {"DX",           Dx },
933        {"DY",           Dy },
934        {"DZ",           Dz },
935        {"EASTING",      Dx },
936        {"FLOOR",        Down }, /* alternative name */
937        {"FROM",         Fr },
938        {"FROMCOUNT",    FrCount },
939        {"FROMDEPTH",    FrDepth },
940        {"GRADIENT",     Clino },
941        {"IGNORE",       Ignore },
942        {"IGNOREALL",    IgnoreAll },
943        {"LEFT",         Left },
944        {"LENGTH",       Tape },
945        {"NEWLINE",      Newline },
946        {"NORTHING",     Dy },
947        {"RIGHT",        Right },
948        {"STATION",      Station }, /* Fr&To in multiline */
949        {"TAPE",         Tape }, /* alternative name */
950        {"TO",           To },
951        {"TOCOUNT",      ToCount },
952        {"TODEPTH",      ToDepth },
953        {"UP",           Up },
954        {NULL,           End }
955   };
956
957#define MASK_stns BIT(Fr) | BIT(To) | BIT(Station)
958#define MASK_tape BIT(Tape) | BIT(FrCount) | BIT(ToCount) | BIT(Count)
959#define MASK_dpth BIT(FrDepth) | BIT(ToDepth) | BIT(Depth) | BIT(DepthChange)
960#define MASK_comp BIT(Comp) | BIT(BackComp)
961#define MASK_clin BIT(Clino) | BIT(BackClino)
962
963#define MASK_NORMAL MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_clin
964#define MASK_DIVING MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_dpth
965#define MASK_CARTESIAN MASK_stns | BIT(Dx) | BIT(Dy) | BIT(Dz)
966#define MASK_CYLPOLAR  MASK_stns | BIT(Dir) | MASK_tape | MASK_comp | MASK_dpth
967#define MASK_PASSAGE BIT(Station) | BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down)
968#define MASK_NOSURVEY MASK_stns
969
970   /* readings which may be given for each style */
971   static const unsigned long mask[] = {
972      MASK_NORMAL, MASK_DIVING, MASK_CARTESIAN, MASK_CYLPOLAR, MASK_NOSURVEY,
973      MASK_PASSAGE
974   };
975
976   /* readings which may be omitted for each style */
977   static const unsigned long mask_optional[] = {
978      BIT(Dir) | BIT(Clino) | BIT(BackClino),
979      BIT(Dir),
980      0,
981      BIT(Dir),
982      0,
983      0 /* BIT(Left) | BIT(Right) | BIT(Up) | BIT(Down), */
984   };
985
986   /* all valid readings */
987   static const unsigned long mask_all[] = {
988      MASK_NORMAL | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
989      MASK_DIVING | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
990      MASK_CARTESIAN | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
991      MASK_CYLPOLAR | BIT(Newline) | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
992      MASK_NOSURVEY | BIT(Ignore) | BIT(IgnoreAll) | BIT(End),
993      MASK_PASSAGE | BIT(Ignore) | BIT(IgnoreAll) | BIT(End)
994   };
995#define STYLE_DEFAULT   -2
996#define STYLE_UNKNOWN   -1
997
998   static sztok styletab[] = {
999        {"CARTESIAN",    STYLE_CARTESIAN },
1000        {"CYLPOLAR",     STYLE_CYLPOLAR },
1001        {"DEFAULT",      STYLE_DEFAULT },
1002        {"DIVING",       STYLE_DIVING },
1003        {"NORMAL",       STYLE_NORMAL },
1004        {"NOSURVEY",     STYLE_NOSURVEY },
1005        {"PASSAGE",      STYLE_PASSAGE },
1006        {"TOPOFIL",      STYLE_NORMAL },
1007        {NULL,           STYLE_UNKNOWN }
1008   };
1009
1010#define m_multi (BIT(Station) | BIT(Count) | BIT(Depth))
1011
1012   int style, k = 0, kMac;
1013   reading *new_order, d;
1014   unsigned long mUsed = 0;
1015   char *style_name;
1016
1017   /* after a bad *data command ignore survey data until the next
1018    * *data command to avoid an avalanche of errors */
1019   pcs->style = STYLE_IGNORE;
1020
1021   kMac = 6; /* minimum for NORMAL style */
1022   new_order = osmalloc(kMac * sizeof(reading));
1023
1024   get_token();
1025   style = match_tok(styletab, TABSIZE(styletab));
1026
1027   if (style == STYLE_DEFAULT) {
1028      default_style(pcs);
1029      return;
1030   }
1031
1032   if (style == STYLE_UNKNOWN) {
1033      file.lpos += strlen(buffer);
1034      compile_error_skip(-/*Data style “%s” unknown*/65, buffer);
1035      return;
1036   }
1037
1038   skipblanks();
1039#ifndef NO_DEPRECATED
1040   /* Olde syntax had optional field for survey grade, so allow an omit
1041    * but issue a warning about it */
1042   if (isOmit(ch)) {
1043      static int data_depr_count = 0;
1044      if (data_depr_count < 5) {
1045         file.lpos += strlen(buffer);
1046         compile_warning(-/*“*data %s %c …” is deprecated - use “*data %s …” instead*/104,
1047                         buffer, ch, buffer);
1048         if (++data_depr_count == 5)
1049            compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
1050      }
1051      nextch();
1052   }
1053#endif
1054
1055   style_name = osstrdup(buffer);
1056   do {
1057      filepos fp;
1058      get_pos(&fp);
1059      get_token();
1060      d = match_tok(dtab, TABSIZE(dtab));
1061      /* only token allowed after IGNOREALL is NEWLINE */
1062      if (k && new_order[k - 1] == IgnoreAll && d != Newline) {
1063         set_pos(&fp);
1064         break;
1065      }
1066      /* Note: an unknown token is reported as trailing garbage */
1067      if (!TSTBIT(mask_all[style], d)) {
1068         file.lpos += strlen(buffer);
1069         compile_error_skip(-/*Reading “%s” not allowed in data style “%s”*/63,
1070                       buffer, style_name);
1071         osfree(style_name);
1072         osfree(new_order);
1073         return;
1074      }
1075      if (TSTBIT(mUsed, Newline) && TSTBIT(m_multi, d)) {
1076         /* e.g. "*data diving station newline tape depth compass" */
1077         file.lpos += strlen(buffer);
1078         compile_error_skip(-/*Reading “%s” must occur before NEWLINE*/225, buffer);
1079         osfree(style_name);
1080         osfree(new_order);
1081         return;
1082      }
1083      /* Check for duplicates unless it's a special reading:
1084       *   IGNOREALL,IGNORE (duplicates allowed) ; END (not possible)
1085       */
1086      if (!((BIT(Ignore) | BIT(End) | BIT(IgnoreAll)) & BIT(d))) {
1087         if (TSTBIT(mUsed, d)) {
1088            file.lpos += strlen(buffer);
1089            compile_error_skip(-/*Duplicate reading “%s”*/67, buffer);
1090            osfree(style_name);
1091            osfree(new_order);
1092            return;
1093         } else {
1094            /* Check for previously listed readings which are incompatible
1095             * with this one - e.g. Count vs FrCount */
1096            bool fBad = fFalse;
1097            switch (d) {
1098             case Station:
1099               if (mUsed & (BIT(Fr) | BIT(To))) fBad = fTrue;
1100               break;
1101             case Fr: case To:
1102               if (TSTBIT(mUsed, Station)) fBad = fTrue;
1103               break;
1104             case Count:
1105               if (mUsed & (BIT(FrCount) | BIT(ToCount) | BIT(Tape)))
1106                  fBad = fTrue;
1107               break;
1108             case FrCount: case ToCount:
1109               if (mUsed & (BIT(Count) | BIT(Tape)))
1110                  fBad = fTrue;
1111               break;
1112             case Depth:
1113               if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(DepthChange)))
1114                  fBad = fTrue;
1115               break;
1116             case FrDepth: case ToDepth:
1117               if (mUsed & (BIT(Depth) | BIT(DepthChange))) fBad = fTrue;
1118               break;
1119             case DepthChange:
1120               if (mUsed & (BIT(FrDepth) | BIT(ToDepth) | BIT(Depth)))
1121                  fBad = fTrue;
1122               break;
1123             case Newline:
1124               if (mUsed & ~m_multi) {
1125                  /* e.g. "*data normal from to tape newline compass clino" */
1126                  file.lpos += strlen(buffer);
1127                  compile_error_skip(-/*NEWLINE can only be preceded by STATION, DEPTH, and COUNT*/226);
1128                  osfree(style_name);
1129                  osfree(new_order);
1130                  return;
1131               }
1132               if (k == 0) {
1133                  file.lpos += strlen(buffer);
1134                  compile_error_skip(-/*NEWLINE can’t be the first reading*/222);
1135                  osfree(style_name);
1136                  osfree(new_order);
1137                  return;
1138               }
1139               break;
1140             default: /* avoid compiler warnings about unhandled enums */
1141               break;
1142            }
1143            if (fBad) {
1144               /* Not entirely happy with phrasing this... */
1145               file.lpos += strlen(buffer);
1146               compile_error_skip(-/*Reading “%s” duplicates previous reading(s)*/77,
1147                             buffer);
1148               osfree(style_name);
1149               osfree(new_order);
1150               return;
1151            }
1152            mUsed |= BIT(d); /* used to catch duplicates */
1153         }
1154      }
1155      if (k && new_order[k - 1] == IgnoreAll) {
1156         SVX_ASSERT(d == Newline);
1157         k--;
1158         d = IgnoreAllAndNewLine;
1159      }
1160      if (k >= kMac) {
1161         kMac = kMac * 2;
1162         new_order = osrealloc(new_order, kMac * sizeof(reading));
1163      }
1164      new_order[k++] = d;
1165   } while (d != End);
1166
1167   if (k >= 2 && new_order[k - 2] == Newline) {
1168      file.lpos += strlen(buffer);
1169      compile_error_skip(-/*NEWLINE can’t be the last reading*/223);
1170      osfree(style_name);
1171      osfree(new_order);
1172      return;
1173   }
1174
1175   if (style == STYLE_NOSURVEY) {
1176      if (TSTBIT(mUsed, Station)) {
1177         if (k >= kMac) {
1178            kMac = kMac * 2;
1179            new_order = osrealloc(new_order, kMac * sizeof(reading));
1180         }
1181         new_order[k - 1] = Newline;
1182         new_order[k++] = End;
1183      }
1184   } else if (style == STYLE_PASSAGE) {
1185      /* Station doesn't mean "multiline" for STYLE_PASSAGE. */
1186   } else if (!TSTBIT(mUsed, Newline) && (m_multi & mUsed)) {
1187      /* This is for when they write
1188       * *data normal station tape compass clino
1189       * (i.e. no newline, but interleaved readings)
1190       */
1191      compile_error_skip(/*Interleaved readings, but no NEWLINE*/224);
1192      osfree(style_name);
1193      osfree(new_order);
1194      return;
1195   }
1196
1197#if 0
1198   printf("mUsed = 0x%x\n", mUsed);
1199#endif
1200
1201   /* Check the supplied readings form a sufficient set. */
1202   if (style != STYLE_PASSAGE) {
1203       if (mUsed & (BIT(Fr) | BIT(To)))
1204           mUsed |= BIT(Station);
1205       else if (TSTBIT(mUsed, Station))
1206           mUsed |= BIT(Fr) | BIT(To);
1207   }
1208
1209   if (mUsed & (BIT(Comp) | BIT(BackComp)))
1210      mUsed |= BIT(Comp) | BIT(BackComp);
1211
1212   if (mUsed & (BIT(Clino) | BIT(BackClino)))
1213      mUsed |= BIT(Clino) | BIT(BackClino);
1214
1215   if (mUsed & (BIT(FrDepth) | BIT(ToDepth)))
1216      mUsed |= BIT(Depth) | BIT(DepthChange);
1217   else if (TSTBIT(mUsed, Depth))
1218      mUsed |= BIT(FrDepth) | BIT(ToDepth) | BIT(DepthChange);
1219   else if (TSTBIT(mUsed, DepthChange))
1220      mUsed |= BIT(FrDepth) | BIT(ToDepth) | BIT(Depth);
1221
1222   if (mUsed & (BIT(FrCount) | BIT(ToCount)))
1223      mUsed |= BIT(Count) | BIT(Tape);
1224   else if (TSTBIT(mUsed, Count))
1225      mUsed |= BIT(FrCount) | BIT(ToCount) | BIT(Tape);
1226   else if (TSTBIT(mUsed, Tape))
1227      mUsed |= BIT(FrCount) | BIT(ToCount) | BIT(Count);
1228
1229#if 0
1230   printf("mUsed = 0x%x, opt = 0x%x, mask = 0x%x\n", mUsed,
1231          mask_optional[style], mask[style]);
1232#endif
1233
1234   if (((mUsed &~ BIT(Newline)) | mask_optional[style]) != mask[style]) {
1235      /* Test should only fail with too few bits set, not too many */
1236      SVX_ASSERT((((mUsed &~ BIT(Newline)) | mask_optional[style])
1237              &~ mask[style]) == 0);
1238      compile_error_skip(/*Too few readings for data style “%s”*/64, style_name);
1239      osfree(style_name);
1240      osfree(new_order);
1241      return;
1242   }
1243
1244   /* don't free default ordering or ordering used by parent */
1245   if (pcs->ordering != default_order &&
1246       !(pcs->next && pcs->next->ordering == pcs->ordering))
1247      osfree(pcs->ordering);
1248
1249   pcs->style = style;
1250   pcs->ordering = new_order;
1251
1252   osfree(style_name);
1253
1254   if (style == STYLE_PASSAGE) {
1255      lrudlist * new_psg = osnew(lrudlist);
1256      new_psg->tube = NULL;
1257      new_psg->next = model;
1258      model = new_psg;
1259      next_lrud = &(new_psg->tube);
1260   }
1261}
1262
1263static void
1264cmd_units(void)
1265{
1266   int units, quantity;
1267   unsigned long qmask;
1268   unsigned long m; /* mask with bit x set to indicate quantity x specified */
1269   real factor;
1270
1271   qmask = get_qlist(0);
1272   if (!qmask) return;
1273   if (qmask == BIT(Q_DEFAULT)) {
1274      default_units(pcs);
1275      return;
1276   }
1277
1278   factor = read_numeric(fTrue, NULL);
1279   if (factor == 0.0) {
1280      compile_error_skip(-/**UNITS factor must be non-zero*/200);
1281      return;
1282   }
1283   if (factor == HUGE_REAL) factor = (real)1.0;
1284
1285   units = get_units(qmask, fTrue);
1286   if (units == UNITS_NULL) return;
1287   if (TSTBIT(qmask, Q_GRADIENT))
1288      pcs->f_clino_percent = (units == UNITS_PERCENT);
1289   if (TSTBIT(qmask, Q_BACKGRADIENT))
1290      pcs->f_backclino_percent = (units == UNITS_PERCENT);
1291
1292   factor *= factor_tab[units];
1293
1294   for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1295      if (qmask & m) pcs->units[quantity] = factor;
1296}
1297
1298static void
1299cmd_calibrate(void)
1300{
1301   real sc, z;
1302   unsigned long qmask, m;
1303   int quantity;
1304
1305   qmask = get_qlist(BIT(Q_POS)|BIT(Q_PLUMB)|BIT(Q_LEVEL));
1306   if (!qmask) return; /* error already reported */
1307
1308   if (qmask == BIT(Q_DEFAULT)) {
1309      default_calib(pcs);
1310      return;
1311   }
1312
1313   if (((qmask & LEN_QMASK)) && ((qmask & ANG_QMASK))) {
1314      compile_error_skip(/*Can’t calibrate angular and length quantities together*/227);
1315      return;
1316   }
1317
1318   z = read_numeric(fFalse, NULL);
1319   sc = read_numeric(fTrue, NULL);
1320   if (sc == HUGE_REAL) sc = (real)1.0;
1321   /* check for declination scale */
1322   /* perhaps "*calibrate declination XXX" should be "*declination XXX" ? */
1323   if (TSTBIT(qmask, Q_DECLINATION) && sc != 1.0) {
1324      compile_error_skip(-/*Scale factor must be 1.0 for DECLINATION*/40);
1325      return;
1326   }
1327   if (sc == 0.0) {
1328      compile_error_skip(-/*Scale factor must be non-zero*/391);
1329      return;
1330   }
1331   for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1) {
1332      if (qmask & m) {
1333         pcs->z[quantity] = pcs->units[quantity] * z;
1334         pcs->sc[quantity] = sc;
1335      }
1336   }
1337}
1338
1339#ifndef NO_DEPRECATED
1340static void
1341cmd_default(void)
1342{
1343   static sztok defaulttab[] = {
1344      { "CALIBRATE", CMD_CALIBRATE },
1345      { "DATA",      CMD_DATA },
1346      { "UNITS",     CMD_UNITS },
1347      { NULL,        CMD_NULL }
1348   };
1349   static int default_depr_count = 0;
1350
1351   if (default_depr_count < 5) {
1352      compile_warning(-/**DEFAULT is deprecated - use *CALIBRATE/DATA/SD/UNITS with argument DEFAULT instead*/20);
1353      if (++default_depr_count == 5)
1354         compile_warning(/*Further uses of this deprecated feature will not be reported*/95);
1355   }
1356
1357   get_token();
1358   switch (match_tok(defaulttab, TABSIZE(defaulttab))) {
1359    case CMD_CALIBRATE:
1360      default_calib(pcs);
1361      break;
1362    case CMD_DATA:
1363      default_style(pcs);
1364      default_grade(pcs);
1365      break;
1366    case CMD_UNITS:
1367      default_units(pcs);
1368      break;
1369    default:
1370      file.lpos += strlen(buffer);
1371      compile_error_skip(-/*Unknown setting “%s”*/41, buffer);
1372   }
1373}
1374#endif
1375
1376static void
1377cmd_include(void)
1378{
1379   char *pth, *fnm = NULL;
1380   int fnm_len;
1381#ifndef NO_DEPRECATED
1382   prefix *root_store;
1383#endif
1384   int ch_store;
1385
1386   pth = path_from_fnm(file.filename);
1387
1388   read_string(&fnm, &fnm_len);
1389
1390#ifndef NO_DEPRECATED
1391   /* Since *begin / *end nesting cannot cross file boundaries we only
1392    * need to preserve the prefix if the deprecated *prefix command
1393    * can be used */
1394   root_store = root;
1395   root = pcs->Prefix; /* Root for include file is current prefix */
1396#endif
1397   ch_store = ch;
1398
1399   data_file(pth, fnm);
1400
1401#ifndef NO_DEPRECATED
1402   root = root_store; /* and restore root */
1403#endif
1404   ch = ch_store;
1405
1406   s_free(&fnm);
1407   osfree(pth);
1408}
1409
1410static void
1411cmd_sd(void)
1412{
1413   real sd, variance;
1414   int units;
1415   unsigned long qmask, m;
1416   int quantity;
1417   qmask = get_qlist(BIT(Q_DECLINATION));
1418   if (!qmask) return; /* no quantities found - error already reported */
1419
1420   if (qmask == BIT(Q_DEFAULT)) {
1421      default_grade(pcs);
1422      return;
1423   }
1424   sd = read_numeric(fFalse, NULL);
1425   if (sd <= (real)0.0) {
1426      compile_error_skip(-/*Standard deviation must be positive*/48);
1427      return;
1428   }
1429   units = get_units(qmask, fFalse);
1430   if (units == UNITS_NULL) return;
1431
1432   sd *= factor_tab[units];
1433   variance = sqrd(sd);
1434
1435   for (quantity = 0, m = BIT(quantity); m <= qmask; quantity++, m <<= 1)
1436      if (qmask & m) pcs->Var[quantity] = variance;
1437}
1438
1439static void
1440cmd_title(void)
1441{
1442   if (!fExplicitTitle && pcs->Prefix == root) {
1443       /* If we don't have an explicit title yet, and we're currently in the
1444        * root prefix, use this title explicitly. */
1445      fExplicitTitle = fTrue;
1446      read_string(&survey_title, &survey_title_len);
1447   } else {
1448      /* parse and throw away this title (but still check rest of line) */
1449      char *s = NULL;
1450      int len;
1451      read_string(&s, &len);
1452      s_free(&s);
1453   }
1454}
1455
1456static sztok case_tab[] = {
1457     {"PRESERVE", OFF},
1458     {"TOLOWER",  LOWER},
1459     {"TOUPPER",  UPPER},
1460     {NULL,       -1}
1461};
1462
1463static void
1464cmd_case(void)
1465{
1466   int setting;
1467   get_token();
1468   setting = match_tok(case_tab, TABSIZE(case_tab));
1469   if (setting != -1) {
1470      pcs->Case = setting;
1471   } else {
1472      file.lpos += strlen(buffer);
1473      compile_error_skip(-/*Found “%s”, expecting “PRESERVE”, “TOUPPER”, or “TOLOWER”*/10,
1474                         buffer);
1475   }
1476}
1477
1478static sztok infer_tab[] = {
1479     { "EQUATES",       INFER_EQUATES },
1480     { "EXPORTS",       INFER_EXPORTS },
1481     { "PLUMBS",        INFER_PLUMBS },
1482#if 0 /* FIXME */
1483     { "SUBSURVEYS",    INFER_SUBSURVEYS },
1484#endif
1485     { NULL,            INFER_NULL }
1486};
1487
1488static sztok onoff_tab[] = {
1489     { "OFF", 0 },
1490     { "ON",  1 },
1491     { NULL, -1 }
1492};
1493
1494static void
1495cmd_infer(void)
1496{
1497   infer_what setting;
1498   int on;
1499   get_token();
1500   setting = match_tok(infer_tab, TABSIZE(infer_tab));
1501   if (setting == INFER_NULL) {
1502      file.lpos += strlen(buffer);
1503      compile_error_skip(-/*Found “%s”, expecting “EQUATES”, “EXPORTS”, or “PLUMBS”*/31, buffer);
1504      return;
1505   }
1506   get_token();
1507   on = match_tok(onoff_tab, TABSIZE(onoff_tab));
1508   if (on == -1) {
1509      file.lpos += strlen(buffer);
1510      compile_error_skip(-/*Found “%s”, expecting “ON” or “OFF”*/32, buffer);
1511      return;
1512   }
1513
1514   if (on) {
1515      pcs->infer |= BIT(setting);
1516      if (setting == INFER_EXPORTS) fExportUsed = fTrue;
1517   } else {
1518      pcs->infer &= ~BIT(setting);
1519   }
1520}
1521
1522static void
1523cmd_truncate(void)
1524{
1525   unsigned int truncate_at = 0; /* default is no truncation */
1526   filepos fp;
1527
1528   get_pos(&fp);
1529
1530   get_token();
1531   if (strcmp(ucbuffer, "OFF") != 0) {
1532      if (*ucbuffer) set_pos(&fp);
1533      truncate_at = read_uint();
1534   }
1535   /* for backward compatibility, "*truncate 0" means "*truncate off" */
1536   pcs->Truncate = (truncate_at == 0) ? INT_MAX : truncate_at;
1537}
1538
1539static void
1540cmd_require(void)
1541{
1542   const unsigned int version[] = {COMMAVERSION};
1543   const unsigned int *ver = version;
1544   filepos fp;
1545
1546   skipblanks();
1547   get_pos(&fp);
1548   while (1) {
1549      int diff = *ver++ - read_uint();
1550      if (diff > 0) break;
1551      if (diff < 0) {
1552         size_t i, len;
1553         char *v;
1554         filepos fp_tmp;
1555
1556         /* find end of version number */
1557         while (isdigit(ch) || ch == '.') nextch();
1558         get_pos(&fp_tmp);
1559         len = (size_t)(fp_tmp.offset - fp.offset);
1560         v = osmalloc(len + 1);
1561         set_pos(&fp);
1562         for (i = 0; i < len; i++) {
1563            v[i] = ch;
1564            nextch();
1565         }
1566         v[i] = '\0';
1567         fatalerror_in_file(file.filename, file.line, /*Survex version %s or greater required to process this survey data.*/2, v);
1568      }
1569      if (ch != '.') break;
1570      nextch();
1571      if (!isdigit(ch) || ver == version + sizeof(version)) break;
1572   }
1573   /* skip rest of version number */
1574   while (isdigit(ch) || ch == '.') nextch();
1575}
1576
1577/* allocate new meta_data if need be */
1578void
1579copy_on_write_meta(settings *s)
1580{
1581   if (!s->meta || s->meta->ref_count != 0) {
1582       meta_data * meta_new = osnew(meta_data);
1583       if (!s->meta) {
1584           meta_new->days1 = meta_new->days2 = -1;
1585       } else {
1586           *meta_new = *(s->meta);
1587       }
1588       meta_new->ref_count = 0;
1589       s->meta = meta_new;
1590   }
1591}
1592
1593static void
1594cmd_date(void)
1595{
1596    int year, month, day;
1597    int days1, days2;
1598    bool implicit_range = fFalse;
1599
1600    read_date(&year, &month, &day);
1601    days1 = days_since_1900(year, month ? month : 1, day ? day : 1);
1602
1603    if (days1 > current_days_since_1900) {
1604        compile_warning(-/*Date is in the future!*/80);
1605    }
1606
1607    skipblanks();
1608    if (ch == '-') {
1609        nextch();
1610        read_date(&year, &month, &day);
1611    } else {
1612        if (month && day) {
1613            days2 = days1;
1614            goto read;
1615        }
1616        implicit_range = fTrue;
1617    }
1618
1619    if (month == 0) month = 12;
1620    if (day == 0) day = last_day(year, month);
1621    days2 = days_since_1900(year, month, day);
1622
1623    if (!implicit_range && days2 > current_days_since_1900) {
1624        compile_warning(-/*Date is in the future!*/80);
1625    }
1626
1627    if (days2 < days1) {
1628        compile_error(-/*End of date range is before the start*/81);
1629    }
1630
1631read:
1632    copy_on_write_meta(pcs);
1633    pcs->meta->days1 = days1;
1634    pcs->meta->days2 = days2;
1635}
1636
1637typedef void (*cmd_fn)(void);
1638
1639static cmd_fn cmd_funcs[] = {
1640   cmd_alias,
1641   cmd_begin,
1642   cmd_calibrate,
1643   cmd_case,
1644   skipline, /*cmd_copyright,*/
1645   cmd_data,
1646   cmd_date,
1647#ifndef NO_DEPRECATED
1648   cmd_default,
1649#endif
1650   cmd_end,
1651   cmd_entrance,
1652   cmd_equate,
1653   cmd_export,
1654   cmd_fix,
1655   cmd_flags,
1656   cmd_include,
1657   cmd_infer,
1658   skipline, /*cmd_instrument,*/
1659#ifndef NO_DEPRECATED
1660   cmd_prefix,
1661#endif
1662   cmd_require,
1663   cmd_sd,
1664   cmd_set,
1665   solve_network,
1666   skipline, /*cmd_team,*/
1667   cmd_title,
1668   cmd_truncate,
1669   cmd_units
1670};
1671
1672extern void
1673handle_command(void)
1674{
1675   int cmdtok;
1676   get_token();
1677   cmdtok = match_tok(cmd_tab, TABSIZE(cmd_tab));
1678
1679   if (cmdtok < 0 || cmdtok >= (int)(sizeof(cmd_funcs) / sizeof(cmd_fn))) {
1680      file.lpos += strlen(buffer);
1681      compile_error_skip(-/*Unknown command “%s”*/12, buffer);
1682      return;
1683   }
1684
1685   switch (cmdtok) {
1686    case CMD_EXPORT:
1687      if (!f_export_ok)
1688         compile_error(/**EXPORT must immediately follow “*BEGIN <SURVEY>”*/57);
1689      break;
1690    case CMD_COPYRIGHT:
1691    case CMD_DATE:
1692    case CMD_INSTRUMENT:
1693    case CMD_TEAM:
1694    case CMD_TITLE:
1695      /* These can occur between *begin and *export */
1696      break;
1697    default:
1698      /* NB: additional handling for "*begin <survey>" in cmd_begin */
1699      f_export_ok = fFalse;
1700      break;
1701   }
1702
1703   cmd_funcs[cmdtok]();
1704}
Note: See TracBrowser for help on using the repository browser.