source: git/src/datain.c @ f6bdb01

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since f6bdb01 was 850fdc4, checked in by Olly Betts <olly@…>, 11 years ago

src/datain.c,tests/: Add support for 'L' flag (exclude from length)
in Compass .dat files - this handled in the same way as the
"DUPLICATE" flag in .svx files.

  • Property mode set to 100644
File size: 49.3 KB
Line 
1/* datain.c
2 * Reads in survey files, dealing with special characters, keywords & data
3 * Copyright (C) 1991-2003,2005,2009,2010,2011,2012,2013,2014 Olly Betts
4 * Copyright (C) 2004 Simeon Warner
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19 */
20
21#ifdef HAVE_CONFIG_H
22#include <config.h>
23#endif
24
25#include <limits.h>
26#include <stdarg.h>
27
28#include "debug.h"
29#include "cavern.h"
30#include "date.h"
31#include "filename.h"
32#include "message.h"
33#include "filelist.h"
34#include "netbits.h"
35#include "netskel.h"
36#include "readval.h"
37#include "datain.h"
38#include "commands.h"
39#include "out.h"
40#include "str.h"
41
42#define EPSILON (REAL_EPSILON * 1000)
43
44#define var(I) (pcs->Var[(I)])
45
46/* true if x is not-a-number value in Compass (999.0 or -999.0)    */
47/* Compass uses 999.0 but understands Karst data which used -999.0 */
48#define is_compass_NaN(x) ( fabs(fabs(x)-999.0) <  EPSILON )
49
50int ch;
51
52typedef enum {
53    CTYPE_OMIT, CTYPE_READING, CTYPE_PLUMB, CTYPE_INFERPLUMB, CTYPE_HORIZ
54} clino_type;
55
56/* Don't explicitly initialise as we can't set the jmp_buf - this has
57 * static scope so will be initialised like this anyway */
58parse file /* = { NULL, NULL, 0, fFalse, NULL } */ ;
59
60bool f_export_ok;
61
62static real value[Fr - 1];
63#define VAL(N) value[(N)-1]
64static real variance[Fr - 1];
65#define VAR(N) variance[(N)-1]
66
67/* style functions */
68static void data_normal(void);
69static void data_cartesian(void);
70static void data_passage(void);
71static void data_nosurvey(void);
72static void data_ignore(void);
73
74void
75get_pos(filepos *fp)
76{
77   fp->ch = ch;
78   fp->offset = ftell(file.fh);
79   if (fp->offset == -1)
80      fatalerror_in_file(file.filename, 0, /*Error reading file*/18);
81}
82
83void
84set_pos(const filepos *fp)
85{
86   ch = fp->ch;
87   if (fseek(file.fh, fp->offset, SEEK_SET) == -1)
88      fatalerror_in_file(file.filename, 0, /*Error reading file*/18);
89}
90
91static void
92push_back(int c)
93{
94   if (c != EOF && ungetc(c, file.fh) == EOF)
95      fatalerror_in_file(file.filename, 0, /*Error reading file*/18);
96}
97
98static void
99report_parent(parse * p) {
100    if (p->parent)
101        report_parent(p->parent);
102    /* Force re-report of include tree for further errors in
103     * parent files */
104    p->reported_where = fFalse;
105    /* TRANSLATORS: %s is replaced by the filename of the parent file, and %u
106     * by the line number in that file. */
107    fprintf(STDERR, msg(/*In file included from %s:%u:\n*/5), p->filename, p->line);
108}
109
110static void
111error_list_parent_files(void)
112{
113   if (!file.reported_where && file.parent) {
114      report_parent(file.parent);
115      /* Suppress reporting of full include tree for further errors
116       * in this file */
117      file.reported_where = fTrue;
118   }
119}
120
121void
122compile_error(int en, ...)
123{
124   int col = 0;
125   va_list ap;
126   va_start(ap, en);
127   error_list_parent_files();
128   if (en < 0) {
129      en = -en;
130      col = ftell(file.fh) - file.lpos;
131   }
132   v_report(1, file.filename, file.line, col, en, ap);
133   va_end(ap);
134}
135
136void
137compile_error_skip(int en, ...)
138{
139   int col = 0;
140   va_list ap;
141   va_start(ap, en);
142   error_list_parent_files();
143   if (en < 0) {
144      en = -en;
145      col = ftell(file.fh) - file.lpos;
146   }
147   v_report(1, file.filename, file.line, col, en, ap);
148   va_end(ap);
149   skipline();
150}
151
152void
153compile_error_token(int en)
154{
155   char *p = NULL;
156   int len = 0;
157   skipblanks();
158   while (!isBlank(ch) && !isEol(ch)) {
159      s_catchar(&p, &len, (char)ch);
160      nextch();
161   }
162   compile_error(en, p ? p : "");
163   osfree(p);
164}
165
166void
167compile_warning(int en, ...)
168{
169   int col = 0;
170   va_list ap;
171   va_start(ap, en);
172   error_list_parent_files();
173   if (en < 0) {
174      en = -en;
175      col = ftell(file.fh) - file.lpos;
176   }
177   v_report(0, file.filename, file.line, col, en, ap);
178   va_end(ap);
179}
180
181/* This function makes a note where to put output files */
182static void
183using_data_file(const char *fnm)
184{
185   if (!fnm_output_base) {
186      /* was: fnm_output_base = base_from_fnm(fnm); */
187      fnm_output_base = baseleaf_from_fnm(fnm);
188   } else if (fnm_output_base_is_dir) {
189      /* --output pointed to directory so use the leaf basename in that dir */
190      char *lf, *p;
191      lf = baseleaf_from_fnm(fnm);
192      p = use_path(fnm_output_base, lf);
193      osfree(lf);
194      osfree(fnm_output_base);
195      fnm_output_base = p;
196      fnm_output_base_is_dir = 0;
197   }
198}
199
200static void
201skipword(void)
202{
203   while (!isBlank(ch) && !isEol(ch)) nextch();
204}
205
206extern void
207skipblanks(void)
208{
209   while (isBlank(ch)) nextch();
210}
211
212extern void
213skipline(void)
214{
215   while (!isEol(ch)) nextch();
216}
217
218#ifndef NO_PERCENTAGE
219static long int filelen;
220#endif
221
222static void
223process_bol(void)
224{
225#ifndef NO_PERCENTAGE
226   /* print %age of file done */
227   if (filelen > 0) {
228      filepos fp;
229      get_pos(&fp);
230      printf("%d%%\r", (int)(100 * fp.offset / filelen));
231   }
232#endif
233
234   nextch();
235   skipblanks();
236}
237
238static void
239process_eol(void)
240{
241   int eolchar;
242
243   skipblanks();
244
245   if (!isEol(ch)) {
246      if (!isComm(ch)) compile_error(-/*End of line not blank*/15);
247      skipline();
248   }
249
250   eolchar = ch;
251   file.line++;
252   /* skip any different eol characters so we get line counts correct on
253    * DOS text files and similar, but don't count several adjacent blank
254    * lines as one */
255   while (ch != EOF) {
256      nextch();
257      if (ch == eolchar || !isEol(ch)) {
258         push_back(ch);
259         break;
260      }
261   }
262   file.lpos = ftell(file.fh);
263}
264
265static bool
266process_non_data_line(void)
267{
268   process_bol();
269
270   if (isData(ch)) return fFalse;
271
272   if (isKeywd(ch)) {
273      nextch();
274      handle_command();
275   }
276
277   process_eol();
278
279   return fTrue;
280}
281
282static void
283read_reading(reading r, bool f_optional)
284{
285   int n_readings;
286   q_quantity q;
287   switch (r) {
288      case Tape: q = Q_LENGTH; break;
289      case Comp: q = Q_BEARING; break;
290      case BackComp: q = Q_BACKBEARING; break;
291      case Clino: q = Q_GRADIENT; break;
292      case BackClino: q = Q_BACKGRADIENT; break;
293      case FrDepth: case ToDepth: q = Q_DEPTH; break;
294      case Dx: q = Q_DX; break;
295      case Dy: q = Q_DY; break;
296      case Dz: q = Q_DZ; break;
297      case FrCount: case ToCount: q = Q_COUNT; break;
298      case Left: q = Q_LEFT; break;
299      case Right: q = Q_RIGHT; break;
300      case Up: q = Q_UP; break;
301      case Down: q = Q_DOWN; break;
302      default:
303        q = Q_NULL; /* Suppress compiler warning */;
304        BUG("Unexpected case");
305   }
306   VAL(r) = read_numeric(f_optional, &n_readings);
307   VAR(r) = var(q);
308   if (n_readings > 1) VAR(r) /= sqrt(n_readings);
309}
310
311static void
312read_bearing_or_omit(reading r)
313{
314   int n_readings;
315   q_quantity q = Q_NULL;
316   VAL(r) = read_numeric_or_omit(&n_readings);
317   switch (r) {
318      case Comp: q = Q_BEARING; break;
319      case BackComp: q = Q_BACKBEARING; break;
320      default:
321        q = Q_NULL; /* Suppress compiler warning */;
322        BUG("Unexpected case");
323   }
324   VAR(r) = var(q);
325   if (n_readings > 1) VAR(r) /= sqrt(n_readings);
326}
327
328/* For reading Compass MAK files which have a freeform syntax */
329static void
330nextch_handling_eol(void)
331{
332   nextch();
333   while (ch != EOF && isEol(ch)) {
334      process_eol();
335      nextch();
336   }
337}
338
339#define LITLEN(S) (sizeof(S"") - 1)
340#define has_ext(F,L,E) ((L) > LITLEN(E) + 1 &&\
341                        (F)[(L) - LITLEN(E) - 1] == FNM_SEP_EXT &&\
342                        strcasecmp((F) + (L) - LITLEN(E), E) == 0)
343extern void
344data_file(const char *pth, const char *fnm)
345{
346   int begin_lineno_store;
347   parse file_store;
348   volatile enum {FMT_SVX, FMT_DAT, FMT_MAK} fmt = FMT_SVX;
349
350   {
351      char *filename;
352      FILE *fh;
353      size_t len;
354
355      if (!pth) {
356         /* file specified on command line - don't do special translation */
357         fh = fopenWithPthAndExt(pth, fnm, EXT_SVX_DATA, "rb", &filename);
358      } else {
359         fh = fopen_portable(pth, fnm, EXT_SVX_DATA, "rb", &filename);
360      }
361
362      if (fh == NULL) {
363         compile_error(/*Couldn’t open data file “%s”*/24, fnm);
364         return;
365      }
366
367      len = strlen(filename);
368      if (has_ext(filename, len, "dat")) {
369         fmt = FMT_DAT;
370      } else if (has_ext(filename, len, "mak")) {
371         fmt = FMT_MAK;
372      }
373
374      file_store = file;
375      if (file.fh) file.parent = &file_store;
376      file.fh = fh;
377      file.filename = filename;
378      file.line = 1;
379      file.lpos = 0;
380      file.reported_where = fFalse;
381   }
382
383   if (fPercent) printf("%s:\n", fnm);
384
385   using_data_file(file.filename);
386
387   begin_lineno_store = pcs->begin_lineno;
388   pcs->begin_lineno = 0;
389
390#ifndef NO_PERCENTAGE
391   /* Try to find how long the file is...
392    * However, under ANSI fseek( ..., SEEK_END) may not be supported */
393   filelen = 0;
394   if (fPercent) {
395      if (fseek(file.fh, 0l, SEEK_END) == 0) {
396         filepos fp;
397         get_pos(&fp);
398         filelen = fp.offset;
399      }
400      rewind(file.fh); /* reset file ptr to start & clear any error state */
401   }
402#endif
403
404   if (fmt == FMT_DAT) {
405      short *t;
406      int i;
407      settings *pcsNew;
408
409      pcsNew = osnew(settings);
410      *pcsNew = *pcs; /* copy contents */
411      pcsNew->begin_lineno = 0;
412      pcsNew->next = pcs;
413      pcs = pcsNew;
414      default_units(pcs);
415      default_calib(pcs);
416
417      pcs->style = STYLE_NORMAL;
418      pcs->units[Q_LENGTH] = METRES_PER_FOOT;
419      t = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
420
421      t[EOF] = SPECIAL_EOL;
422      memset(t, 0, sizeof(short) * 33);
423      for (i = 33; i < 127; i++) t[i] = SPECIAL_NAMES;
424      t[127] = 0;
425      for (i = 128; i < 256; i++) t[i] = SPECIAL_NAMES;
426      t['\t'] |= SPECIAL_BLANK;
427      t[' '] |= SPECIAL_BLANK;
428      t['\032'] |= SPECIAL_EOL; /* Ctrl-Z, so olde DOS text files are handled ok */
429      t['\n'] |= SPECIAL_EOL;
430      t['\r'] |= SPECIAL_EOL;
431      t['.'] |= SPECIAL_DECIMAL;
432      t['-'] |= SPECIAL_MINUS;
433      t['+'] |= SPECIAL_PLUS;
434      pcs->Translate = t;
435      pcs->Case = OFF;
436      pcs->Truncate = INT_MAX;
437      pcs->infer = 7; /* FIXME: BIT(EQUATES)|BIT(EXPORTS)|BIT(PLUMBS); */
438   } else if (fmt == FMT_MAK) {
439      short *t;
440      int i;
441      settings *pcsNew;
442
443      pcsNew = osnew(settings);
444      *pcsNew = *pcs; /* copy contents */
445      pcsNew->begin_lineno = 0;
446      pcsNew->next = pcs;
447      pcs = pcsNew;
448
449      t = ((short*)osmalloc(ossizeof(short) * 257)) + 1;
450
451      t[EOF] = SPECIAL_EOL;
452      memset(t, 0, sizeof(short) * 33);
453      for (i = 33; i < 127; i++) t[i] = SPECIAL_NAMES;
454      t[127] = 0;
455      for (i = 128; i < 256; i++) t[i] = SPECIAL_NAMES;
456      t['['] = t[','] = t[';'] = 0;
457      t['\t'] |= SPECIAL_BLANK;
458      t[' '] |= SPECIAL_BLANK;
459      t['\032'] |= SPECIAL_EOL; /* Ctrl-Z, so olde DOS text files are handled ok */
460      t['\n'] |= SPECIAL_EOL;
461      t['\r'] |= SPECIAL_EOL;
462      t['.'] |= SPECIAL_DECIMAL;
463      t['-'] |= SPECIAL_MINUS;
464      t['+'] |= SPECIAL_PLUS;
465      pcs->Translate = t;
466      pcs->Case = OFF;
467      pcs->Truncate = INT_MAX;
468   }
469
470#ifdef HAVE_SETJMP_H
471   /* errors in nested functions can longjmp here */
472   if (setjmp(file.jbSkipLine)) {
473      skipline();
474      process_eol();
475   }
476#endif
477
478   if (fmt == FMT_DAT) {
479      while (!feof(file.fh) && !ferror(file.fh)) {
480         static reading compass_order[] = {
481            Fr, To, Tape, CompassDATComp, CompassDATClino,
482            CompassDATLeft, CompassDATRight, CompassDATUp, CompassDATDown,
483            CompassDATFlags, IgnoreAll
484         };
485         static reading compass_order_backsights[] = {
486            Fr, To, Tape, CompassDATComp, CompassDATClino,
487            CompassDATLeft, CompassDATRight, CompassDATUp, CompassDATDown,
488            CompassDATBackComp, CompassDATBackClino,
489            CompassDATFlags, IgnoreAll
490         };
491         /* <Cave name> */
492         process_bol();
493         skipline();
494         process_eol();
495         /* SURVEY NAME: <Short name> */
496         get_token();
497         get_token();
498         /* if (ch != ':') ... */
499         nextch();
500         skipblanks();
501         get_token();
502         skipline();
503         process_eol();
504         /* SURVEY DATE: 7 10 79  COMMENT:<Long name> */
505         /* Note: Larry says a 2 digit year is always 19XX */
506         /* NB order is *month* *day* year */
507         get_token();
508         get_token();
509         copy_on_write_meta(pcs);
510         if (ch == ':') {
511             int year, month, day;
512
513             nextch();
514
515             month = read_uint();
516             day = read_uint();
517             year = read_uint();
518             /* Note: Larry says a 2 digit year is always 19XX */
519             if (year < 100) year += 1900;
520
521             pcs->meta->days1 = pcs->meta->days2 = days_since_1900(year, month, day);
522         } else {
523             pcs->meta->days1 = pcs->meta->days2 = -1;
524         }
525         skipline();
526         process_eol();
527         /* SURVEY TEAM: */
528         get_token();
529         get_token();
530         skipline();
531         process_eol();
532         /* <Survey team> */
533         nextch();
534         skipline();
535         process_eol();
536         /* DECLINATION: 1.00  FORMAT: DDDDLUDRADLN  CORRECTIONS: 2.00 3.00 4.00 */
537         get_token();
538         nextch(); /* : */
539         skipblanks();
540         pcs->z[Q_DECLINATION] = -read_numeric(fFalse, NULL);
541         pcs->z[Q_DECLINATION] *= pcs->units[Q_DECLINATION];
542         get_token();
543         pcs->ordering = compass_order;
544         if (strcmp(buffer, "FORMAT") == 0) {
545            nextch(); /* : */
546            get_token();
547            if (strlen(buffer) >= 12 && buffer[11] == 'B') {
548               /* We have backsights for compass and clino */
549               pcs->ordering = compass_order_backsights;
550            }
551            get_token();
552         }
553         if (strcmp(buffer, "CORRECTIONS") == 0) {
554            nextch(); /* : */
555            pcs->z[Q_BEARING] = -rad(read_numeric(fFalse, NULL));
556            pcs->z[Q_GRADIENT] = -rad(read_numeric(fFalse, NULL));
557            pcs->z[Q_LENGTH] = -read_numeric(fFalse, NULL);
558         } else {
559            pcs->z[Q_BEARING] = 0;
560            pcs->z[Q_GRADIENT] = 0;
561            pcs->z[Q_LENGTH] = 0;
562         }
563         skipline();
564         process_eol();
565         /* BLANK LINE */
566         process_bol();
567         skipline();
568         process_eol();
569         /* heading line */
570         process_bol();
571         skipline();
572         process_eol();
573         /* BLANK LINE */
574         process_bol();
575         skipline();
576         process_eol();
577         while (!feof(file.fh)) {
578            process_bol();
579            if (ch == '\x0c') {
580               nextch();
581               process_eol();
582               break;
583            }
584            data_normal();
585         }
586      }
587      {
588         settings *pcsParent = pcs->next;
589         SVX_ASSERT(pcsParent);
590         pcs->ordering = NULL;
591         free_settings(pcs);
592         pcs = pcsParent;
593      }
594   } else if (fmt == FMT_MAK) {
595      nextch_handling_eol();
596      while (!feof(file.fh) && !ferror(file.fh)) {
597         if (ch == '#') {
598            /* include a file */
599            int ch_store;
600            char *dat_pth = path_from_fnm(file.filename);
601            char *dat_fnm = NULL;
602            int dat_fnm_len;
603            nextch_handling_eol();
604            while (ch != ',' && ch != ';' && ch != EOF) {
605               while (isEol(ch)) process_eol();
606               s_catchar(&dat_fnm, &dat_fnm_len, (char)ch);
607               nextch_handling_eol();
608            }
609            while (ch != ';' && ch != EOF) {
610               prefix *name;
611               nextch_handling_eol();
612               name = read_prefix(PFX_STATION|PFX_OPT);
613               if (name) {
614                  skipblanks();
615                  if (ch == '[') {
616                     /* fixed pt */
617                     node *stn;
618                     real x, y, z;
619                     name->sflags |= BIT(SFLAGS_FIXED);
620                     nextch_handling_eol();
621                     while (!isdigit(ch) && ch != '+' && ch != '-' &&
622                            ch != '.' && ch != ']' && ch != EOF) {
623                        nextch_handling_eol();
624                     }
625                     x = read_numeric(fFalse, NULL);
626                     while (!isdigit(ch) && ch != '+' && ch != '-' &&
627                            ch != '.' && ch != ']' && ch != EOF) {
628                        nextch_handling_eol();
629                     }
630                     y = read_numeric(fFalse, NULL);
631                     while (!isdigit(ch) && ch != '+' && ch != '-' &&
632                            ch != '.' && ch != ']' && ch != EOF) {
633                        nextch_handling_eol();
634                     }
635                     z = read_numeric(fFalse, NULL);
636                     stn = StnFromPfx(name);
637                     if (!fixed(stn)) {
638                        POS(stn, 0) = x;
639                        POS(stn, 1) = y;
640                        POS(stn, 2) = z;
641                        fix(stn);
642                     } else {
643                        if (x != POS(stn, 0) || y != POS(stn, 1) ||
644                            z != POS(stn, 2)) {
645                           compile_error(/*Station already fixed or equated to a fixed point*/46);
646                        } else {
647                           compile_warning(/*Station already fixed at the same coordinates*/55);
648                        }
649                     }
650                     while (ch != ']' && ch != EOF) nextch_handling_eol();
651                     if (ch == ']') {
652                        nextch_handling_eol();
653                        skipblanks();
654                     }
655                  } else {
656                     /* FIXME: link station - ignore for now */
657                     /* FIXME: perhaps issue warning? */
658                  }
659                  while (ch != ',' && ch != ';' && ch != EOF)
660                     nextch_handling_eol();
661               }
662            }
663            if (dat_fnm) {
664               ch_store = ch;
665               data_file(dat_pth, dat_fnm);
666               ch = ch_store;
667               osfree(dat_fnm);
668            }
669         } else {
670            /* FIXME: also check for % and $ later */
671            nextch_handling_eol();
672         }
673      }
674      {
675         settings *pcsParent = pcs->next;
676         SVX_ASSERT(pcsParent);
677         free_settings(pcs);
678         pcs = pcsParent;
679      }
680   } else {
681      while (!feof(file.fh) && !ferror(file.fh)) {
682         if (!process_non_data_line()) {
683            f_export_ok = fFalse;
684            switch (pcs->style) {
685             case STYLE_NORMAL:
686             case STYLE_DIVING:
687             case STYLE_CYLPOLAR:
688               data_normal();
689               break;
690             case STYLE_CARTESIAN:
691               data_cartesian();
692               break;
693             case STYLE_PASSAGE:
694               data_passage();
695               break;
696             case STYLE_NOSURVEY:
697               data_nosurvey();
698               break;
699             case STYLE_IGNORE:
700               data_ignore();
701               break;
702             default:
703               BUG("bad style");
704            }
705         }
706      }
707   }
708
709   /* don't allow *BEGIN at the end of a file, then *EXPORT in the
710    * including file */
711   f_export_ok = fFalse;
712
713#ifndef NO_PERCENTAGE
714   if (fPercent) putnl();
715#endif
716
717   if (pcs->begin_lineno) {
718      error_in_file(file.filename, pcs->begin_lineno,
719                    /*BEGIN with no matching END in this file*/23);
720      /* Implicitly close any unclosed BEGINs from this file */
721      do {
722         settings *pcsParent = pcs->next;
723         SVX_ASSERT(pcsParent);
724         free_settings(pcs);
725         pcs = pcsParent;
726      } while (pcs->begin_lineno);
727   }
728
729   pcs->begin_lineno = begin_lineno_store;
730
731   if (ferror(file.fh))
732      fatalerror_in_file(file.filename, 0, /*Error reading file*/18);
733
734   (void)fclose(file.fh);
735
736   file = file_store;
737
738   /* don't free this - it may be pointed to by prefix.file */
739   /* osfree(file.filename); */
740}
741
742static real
743mod2pi(real a)
744{
745   return a - floor(a / (2 * M_PI)) * (2 * M_PI);
746}
747
748static real
749handle_plumb(clino_type *p_ctype)
750{
751   typedef enum {
752      CLINO_NULL=-1, CLINO_UP, CLINO_DOWN, CLINO_LEVEL
753   } clino_tok;
754   static sztok clino_tab[] = {
755      {"D",     CLINO_DOWN},
756      {"DOWN",  CLINO_DOWN},
757      {"H",     CLINO_LEVEL},
758      {"LEVEL", CLINO_LEVEL},
759      {"U",     CLINO_UP},
760      {"UP",    CLINO_UP},
761      {NULL,    CLINO_NULL}
762   };
763   static real clinos[] = {(real)M_PI_2, (real)(-M_PI_2), (real)0.0};
764   clino_tok tok;
765
766   skipblanks();
767   if (isalpha(ch)) {
768      filepos fp;
769      get_pos(&fp);
770      get_token();
771      tok = match_tok(clino_tab, TABSIZE(clino_tab));
772      if (tok != CLINO_NULL) {
773         *p_ctype = (tok == CLINO_LEVEL ? CTYPE_HORIZ : CTYPE_PLUMB);
774         return clinos[tok];
775      }
776      set_pos(&fp);
777   } else if (isSign(ch)) {
778      int chOld = ch;
779      nextch();
780      if (toupper(ch) == 'V') {
781         nextch();
782         *p_ctype = CTYPE_PLUMB;
783         return (!isMinus(chOld) ? M_PI_2 : -M_PI_2);
784      }
785
786      if (isOmit(chOld)) {
787         *p_ctype = CTYPE_OMIT;
788         /* no clino reading, so assume 0 with large sd */
789         return (real)0.0;
790      }
791   } else if (isOmit(ch)) {
792      /* OMIT char may not be a SIGN char too so we need to check here as
793       * well as above... */
794      nextch();
795      *p_ctype = CTYPE_OMIT;
796      /* no clino reading, so assume 0 with large sd */
797      return (real)0.0;
798   }
799   return HUGE_REAL;
800}
801
802static void
803warn_readings_differ(int msgno, real diff)
804{
805   char buf[64];
806   char *p;
807   sprintf(buf, "%.2f", deg(fabs(diff)));
808   p = strchr(buf, '.');
809   if (p) {
810      char *z = p;
811      while (*++p) {
812         if (*p != '0') z = p + 1;
813      }
814      if (*z) *z = '\0';
815   }
816   compile_warning(msgno, buf);
817}
818
819static bool
820handle_comp_units(void)
821{
822   bool fNoComp = fTrue;
823   if (VAL(Comp) != HUGE_REAL) {
824      fNoComp = fFalse;
825      VAL(Comp) *= pcs->units[Q_BEARING];
826      if (VAL(Comp) < (real)0.0 || VAL(Comp) - M_PI * 2.0 > EPSILON) {
827         /* TRANSLATORS: Suspicious means something like 410 degrees or -20
828          * degrees */
829         compile_warning(/*Suspicious compass reading*/59);
830         VAL(Comp) = mod2pi(VAL(Comp));
831      }
832   }
833   if (VAL(BackComp) != HUGE_REAL) {
834      fNoComp = fFalse;
835      VAL(BackComp) *= pcs->units[Q_BACKBEARING];
836      if (VAL(BackComp) < (real)0.0 || VAL(BackComp) - M_PI * 2.0 > EPSILON) {
837         /* FIXME: different message for BackComp? */
838         compile_warning(/*Suspicious compass reading*/59);
839         VAL(BackComp) = mod2pi(VAL(BackComp));
840      }
841   }
842   return fNoComp;
843}
844
845static real
846handle_compass(real *p_var)
847{
848   real compvar = VAR(Comp);
849   real comp = VAL(Comp);
850   real backcomp = VAL(BackComp);
851   if (comp != HUGE_REAL) {
852      comp = (comp - pcs->z[Q_BEARING]) * pcs->sc[Q_BEARING];
853      comp -= pcs->z[Q_DECLINATION];
854   }
855   if (backcomp != HUGE_REAL) {
856      backcomp = (backcomp - pcs->z[Q_BACKBEARING])
857              * pcs->sc[Q_BACKBEARING];
858      backcomp -= pcs->z[Q_DECLINATION];
859      backcomp -= M_PI;
860      if (comp != HUGE_REAL) {
861         real diff = comp - backcomp;
862         real adj = fabs(diff) > M_PI ? M_PI : 0;
863         diff -= floor((diff + M_PI) / (2 * M_PI)) * 2 * M_PI;
864         if (sqrd(diff / 2.0) > compvar + VAR(Q_BACKBEARING)) {
865            /* fore and back readings differ by more than 2 sds */
866            /* TRANSLATORS: Degrees are the angular measurement where there are
867             * 360 in a full circle. */
868            warn_readings_differ(/*COMPASS reading and BACKCOMPASS reading disagree by %s degrees*/98, diff);
869         }
870         comp = (comp / compvar + backcomp / VAR(BackComp));
871         compvar = (compvar + VAR(BackComp)) / 4;
872         comp *= compvar;
873         comp += adj;
874      } else {
875         comp = backcomp;
876         compvar = VAR(BackComp);
877      }
878   }
879   *p_var = compvar;
880   return comp;
881}
882
883static int
884process_normal(prefix *fr, prefix *to, bool fToFirst,
885               clino_type ctype, clino_type backctype)
886{
887   real tape = VAL(Tape);
888   real clin = VAL(Clino);
889   real backclin = VAL(BackClino);
890
891   real dx, dy, dz;
892   real vx, vy, vz;
893#ifndef NO_COVARIANCES
894   real cxy, cyz, czx;
895#endif
896
897   bool fNoComp;
898
899   /* adjusted tape is negative -- probably the calibration is wrong */
900   if (tape < (real)0.0) {
901      /* TRANSLATE different message for topofil? */
902      compile_warning(/*Negative adjusted tape reading*/79);
903   }
904
905   fNoComp = handle_comp_units();
906
907   if (ctype == CTYPE_READING) {
908      bool range_0_180;
909      real z;
910      real diff_from_abs90;
911      clin *= pcs->units[Q_GRADIENT];
912      /* percentage scale */
913      if (pcs->f_clino_percent) clin = atan(clin);
914      /* We want to warn if there's a reading which it would be impossible
915       * to have read from the instrument (e.g. on a -90 to 90 degree scale
916       * you can't read "96" (it's probably a typo for "69").  However, the
917       * gradient reading from a topofil is typically in the range 0 to 180,
918       * with 90 being horizontal.
919       *
920       * Really we should allow the valid range to be specified, but for now
921       * we infer it from the zero error - if this is within 45 degrees of
922       * 90 then we assume the range is 0 to 180.
923       */
924      z = pcs->z[Q_GRADIENT];
925      range_0_180 = (z > M_PI_4 && z < 3*M_PI_4);
926      diff_from_abs90 = fabs(clin) - M_PI_2;
927      if (diff_from_abs90 > EPSILON) {
928         if (!range_0_180)
929            /* TRANSLATORS: Degrees are the angular measurement where there are
930             * 360 in a full circle. */
931            compile_warning(/*Clino reading over 90 degrees (absolute value)*/51);
932      } else if (TSTBIT(pcs->infer, INFER_PLUMBS) &&
933                 diff_from_abs90 >= -EPSILON) {
934         ctype = CTYPE_INFERPLUMB;
935      }
936      if (range_0_180 && ctype != CTYPE_INFERPLUMB) {
937         /* FIXME: Warning message not ideal... */
938         if (clin < 0.0 || clin - M_PI > EPSILON)
939            compile_warning(/*Clino reading over 90 degrees (absolute value)*/51);
940      }
941   }
942
943   if (backctype == CTYPE_READING) {
944      backclin *= pcs->units[Q_BACKGRADIENT];
945      /* percentage scale */
946      if (pcs->f_backclino_percent) backclin = atan(backclin);
947      if (ctype != CTYPE_READING) {
948         real diff_from_abs90 = fabs(backclin) - M_PI_2;
949         if (diff_from_abs90 > EPSILON) {
950            /* FIXME: different message for BackClino? */
951            compile_warning(/*Clino reading over 90 degrees (absolute value)*/51);
952         } else if (TSTBIT(pcs->infer, INFER_PLUMBS) &&
953                    diff_from_abs90 >= -EPSILON) {
954            backctype = CTYPE_INFERPLUMB;
955         }
956      }
957   }
958
959   /* un-infer the plumb if the backsight was just a reading */
960   if (ctype == CTYPE_INFERPLUMB && backctype == CTYPE_READING) {
961       ctype = CTYPE_READING;
962   }
963
964   if (ctype != CTYPE_OMIT && backctype != CTYPE_OMIT && ctype != backctype) {
965      /* TRANSLATORS: In data with backsights, the user has tried to give a
966       * plumb for the foresight and a clino reading for the backsight, or
967       * something similar. */
968      compile_error_skip(/*CLINO and BACKCLINO readings must be of the same type*/84);
969      return 0;
970   }
971
972   if (ctype == CTYPE_PLUMB || ctype == CTYPE_INFERPLUMB ||
973       backctype == CTYPE_PLUMB || backctype == CTYPE_INFERPLUMB) {
974      /* plumbed */
975      if (!fNoComp) {
976         if (ctype == CTYPE_PLUMB ||
977             (ctype == CTYPE_INFERPLUMB && VAL(Comp) != 0.0) ||
978             backctype == CTYPE_PLUMB ||
979             (backctype == CTYPE_INFERPLUMB && VAL(BackComp) != 0.0)) {
980            /* FIXME: Different message for BackComp? */
981            /* TRANSLATORS: A "plumbed leg" is one measured using a plumbline
982             * (a weight on a string).  So the problem here is that the leg is
983             * vertical, so a compass reading has no meaning! */
984            compile_warning(/*Compass reading given on plumbed leg*/21);
985         }
986      }
987
988      dx = dy = (real)0.0;
989      if (ctype != CTYPE_OMIT) {
990         if (backctype != CTYPE_OMIT && (clin > 0) == (backclin > 0)) {
991            /* We've got two UPs or two DOWNs - FIXME: not ideal message */
992            compile_error_skip(/*CLINO and BACKCLINO readings must be of the same type*/84);
993            return 0;
994         }
995         dz = (clin > (real)0.0) ? tape : -tape;
996      } else {
997         dz = (backclin < (real)0.0) ? tape : -tape;
998      }
999      vx = vy = var(Q_POS) / 3.0 + dz * dz * var(Q_PLUMB);
1000      vz = var(Q_POS) / 3.0 + VAR(Tape);
1001#ifndef NO_COVARIANCES
1002      /* Correct values - no covariances in this case! */
1003      cxy = cyz = czx = (real)0.0;
1004#endif
1005   } else {
1006      /* Each of ctype and backctype are either CTYPE_READING/CTYPE_HORIZ
1007       * or CTYPE_OMIT */
1008      /* clino */
1009      real L2, cosG, LcosG, cosG2, sinB, cosB, dx2, dy2, dz2, v, V;
1010      if (fNoComp) {
1011         /* TRANSLATORS: Here "legs" are survey legs, i.e. measurements between
1012          * survey stations. */
1013         compile_error_skip(/*Compass reading may not be omitted except on plumbed legs*/14);
1014         return 0;
1015      }
1016      if (tape == (real)0.0) {
1017         dx = dy = dz = (real)0.0;
1018         vx = vy = vz = (real)(var(Q_POS) / 3.0); /* Position error only */
1019#ifndef NO_COVARIANCES
1020         cxy = cyz = czx = (real)0.0;
1021#endif
1022#if DEBUG_DATAIN_1
1023         printf("Zero length leg: vx = %f, vy = %f, vz = %f\n", vx, vy, vz);
1024#endif
1025      } else {
1026         real sinGcosG;
1027         /* take into account variance in LEVEL case */
1028         real var_clin = var(Q_LEVEL);
1029         real var_comp;
1030         real comp = handle_compass(&var_comp);
1031         /* ctype != CTYPE_READING is LEVEL case */
1032         if (ctype == CTYPE_READING) {
1033            clin = (clin - pcs->z[Q_GRADIENT]) * pcs->sc[Q_GRADIENT];
1034            var_clin = VAR(Clino);
1035         }
1036         if (backctype == CTYPE_READING) {
1037            backclin = (backclin - pcs->z[Q_BACKGRADIENT])
1038               * pcs->sc[Q_BACKGRADIENT];
1039            if (ctype == CTYPE_READING) {
1040               if (sqrd((clin + backclin) / 3.0) > var_clin + VAR(BackClino)) {
1041                  /* fore and back readings differ by more than 3 sds */
1042                  /* TRANSLATORS: Degrees are the angular measurement where
1043                   * there are 360 in a full circle. */
1044                  warn_readings_differ(/*CLINO reading and BACKCLINO reading disagree by %s degrees*/99, clin + backclin);
1045               }
1046               clin = (clin / var_clin - backclin / VAR(BackClino));
1047               var_clin = (var_clin + VAR(BackClino)) / 4;
1048               clin *= var_clin;
1049            } else {
1050               clin = -backclin;
1051               var_clin = VAR(BackClino);
1052            }
1053         }
1054
1055#if DEBUG_DATAIN
1056         printf("    %4.2f %4.2f %4.2f\n", tape, comp, clin);
1057#endif
1058         cosG = cos(clin);
1059         LcosG = tape * cosG;
1060         sinB = sin(comp);
1061         cosB = cos(comp);
1062#if DEBUG_DATAIN_1
1063         printf("sinB = %f, cosG = %f, LcosG = %f\n", sinB, cosG, LcosG);
1064#endif
1065         dx = LcosG * sinB;
1066         dy = LcosG * cosB;
1067         dz = tape * sin(clin);
1068/*      printf("%.2f\n",clin); */
1069#if DEBUG_DATAIN_1
1070         printf("dx = %f\ndy = %f\ndz = %f\n", dx, dy, dz);
1071#endif
1072         dx2 = dx * dx;
1073         L2 = tape * tape;
1074         V = VAR(Tape) / L2;
1075         dy2 = dy * dy;
1076         cosG2 = cosG * cosG;
1077         sinGcosG = sin(clin) * cosG;
1078         dz2 = dz * dz;
1079         v = dz2 * var_clin;
1080#ifdef NO_COVARIANCES
1081         vx = (var(Q_POS) / 3.0 + dx2 * V + dy2 * var_comp +
1082               (.5 + sinB * sinB * cosG2) * v);
1083         vy = (var(Q_POS) / 3.0 + dy2 * V + dx2 * var_comp +
1084               (.5 + cosB * cosB * cosG2) * v);
1085         if (ctype == CTYPE_OMIT && backctype == CTYPE_OMIT) {
1086            /* if no clino, assume sd=tape/sqrt(10) so 3sds = .95*tape */
1087            vz = var(Q_POS) / 3.0 + L2 * (real)0.1;
1088         } else {
1089            vz = var(Q_POS) / 3.0 + dz2 * V + L2 * cosG2 * var_clin;
1090         }
1091         /* for Surveyor87 errors: vx=vy=vz=var(Q_POS)/3.0; */
1092#else
1093         vx = var(Q_POS) / 3.0 + dx2 * V + dy2 * var_comp +
1094            (sinB * sinB * v);
1095         vy = var(Q_POS) / 3.0 + dy2 * V + dx2 * var_comp +
1096            (cosB * cosB * v);
1097         if (ctype == CTYPE_OMIT && backctype == CTYPE_OMIT) {
1098            /* if no clino, assume sd=tape/sqrt(10) so 3sds = .95*tape */
1099            vz = var(Q_POS) / 3.0 + L2 * (real)0.1;
1100         } else {
1101            vz = var(Q_POS) / 3.0 + dz2 * V + L2 * cosG2 * var_clin;
1102         }
1103         /* usual covariance formulae are fine in no clino case since
1104          * dz = 0 so value of var_clin is ignored */
1105         cxy = sinB * cosB * (VAR(Tape) * cosG2 + var_clin * dz2)
1106               - var_comp * dx * dy;
1107         czx = VAR(Tape) * sinB * sinGcosG - var_clin * dx * dz;
1108         cyz = VAR(Tape) * cosB * sinGcosG - var_clin * dy * dz;
1109#if 0
1110         printf("vx = %6.3f, vy = %6.3f, vz = %6.3f\n", vx, vy, vz);
1111         printf("cxy = %6.3f, cyz = %6.3f, czx = %6.3f\n", cxy, cyz, czx);
1112#endif
1113#endif
1114#if DEBUG_DATAIN_1
1115         printf("In DATAIN.C, vx = %f, vy = %f, vz = %f\n", vx, vy, vz);
1116#endif
1117      }
1118   }
1119#if DEBUG_DATAIN_1
1120   printf("Just before addleg, vx = %f\n", vx);
1121#endif
1122   /*printf("dx,dy,dz = %.2f %.2f %.2f\n\n", dx, dy, dz);*/
1123   addlegbyname(fr, to, fToFirst, dx, dy, dz, vx, vy, vz
1124#ifndef NO_COVARIANCES
1125                , cyz, czx, cxy
1126#endif
1127                );
1128   return 1;
1129}
1130
1131static int
1132process_diving(prefix *fr, prefix *to, bool fToFirst, bool fDepthChange)
1133{
1134   real tape = VAL(Tape);
1135
1136   real dx, dy, dz;
1137   real vx, vy, vz;
1138#ifndef NO_COVARIANCES
1139   real cxy = 0, cyz = 0, czx = 0;
1140#endif
1141
1142   handle_comp_units();
1143
1144   /* depth gauge readings increase upwards with default calibration */
1145   if (fDepthChange) {
1146      SVX_ASSERT(VAL(FrDepth) == 0.0);
1147      dz = VAL(ToDepth) * pcs->units[Q_DEPTH] - pcs->z[Q_DEPTH];
1148      dz *= pcs->sc[Q_DEPTH];
1149   } else {
1150      dz = VAL(ToDepth) - VAL(FrDepth);
1151      dz *= pcs->units[Q_DEPTH] * pcs->sc[Q_DEPTH];
1152   }
1153
1154   /* adjusted tape is negative -- probably the calibration is wrong */
1155   if (tape < (real)0.0) {
1156      compile_warning(/*Negative adjusted tape reading*/79);
1157   }
1158
1159   /* check if tape is less than depth change */
1160   if (tape < fabs(dz)) {
1161      /* FIXME: allow margin of error based on variances? */
1162      /* TRANSLATORS: This means that the data fed in said this.
1163       *
1164       * It could be a gross error (e.g. the decimal point is missing from the
1165       * depth gauge reading) or it could just be due to random error on a near
1166       * vertical leg */
1167      compile_warning(/*Tape reading is less than change in depth*/62);
1168   }
1169
1170   if (tape == (real)0.0 && dz == 0.0) {
1171      dx = dy = dz = (real)0.0;
1172      vx = vy = vz = (real)(var(Q_POS) / 3.0); /* Position error only */
1173   } else if (VAL(Comp) == HUGE_REAL &&
1174              VAL(BackComp) == HUGE_REAL) {
1175      /* plumb */
1176      dx = dy = (real)0.0;
1177      if (dz < 0) tape = -tape;
1178      /* FIXME: Should use FrDepth sometimes... */
1179      dz = (dz * VAR(Tape) + tape * 2 * VAR(ToDepth))
1180         / (VAR(Tape) * 2 * VAR(ToDepth));
1181      vx = vy = var(Q_POS) / 3.0 + dz * dz * var(Q_PLUMB);
1182      /* FIXME: Should use FrDepth sometimes... */
1183      vz = var(Q_POS) / 3.0 + VAR(Tape) * 2 * VAR(ToDepth)
1184                              / (VAR(Tape) + VAR(ToDepth));
1185   } else {
1186      real L2, sinB, cosB, dz2, D2;
1187      real var_comp;
1188      real comp = handle_compass(&var_comp);
1189      sinB = sin(comp);
1190      cosB = cos(comp);
1191      L2 = tape * tape;
1192      dz2 = dz * dz;
1193      D2 = L2 - dz2;
1194      if (D2 <= (real)0.0) {
1195         /* FIXME: Should use FrDepth sometimes... */
1196         real vsum = VAR(Tape) + 2 * VAR(ToDepth);
1197         dx = dy = (real)0.0;
1198         vx = vy = var(Q_POS) / 3.0;
1199         /* FIXME: Should use FrDepth sometimes... */
1200         vz = var(Q_POS) / 3.0 + VAR(Tape) * 2 * VAR(ToDepth) / vsum;
1201         if (dz > 0) {
1202            /* FIXME: Should use FrDepth sometimes... */
1203            dz = (dz * VAR(Tape) + tape * 2 * VAR(ToDepth)) / vsum;
1204         } else {
1205            dz = (dz * VAR(Tape) - tape * 2 * VAR(ToDepth)) / vsum;
1206         }
1207      } else {
1208         real D = sqrt(D2);
1209         /* FIXME: Should use FrDepth sometimes... */
1210         real F = VAR(Tape) * L2 + 2 * VAR(ToDepth) * D2;
1211         dx = D * sinB;
1212         dy = D * cosB;
1213
1214         vx = var(Q_POS) / 3.0 +
1215            sinB * sinB * F / D2 + var_comp * dy * dy;
1216         vy = var(Q_POS) / 3.0 +
1217            cosB * cosB * F / D2 + var_comp * dx * dx;
1218         /* FIXME: Should use FrDepth sometimes... */
1219         vz = var(Q_POS) / 3.0 + 2 * VAR(ToDepth);
1220
1221#ifndef NO_COVARIANCES
1222         cxy = sinB * cosB * (F / D2 + var_comp * D2);
1223         /* FIXME: Should use FrDepth sometimes... */
1224         cyz = -2 * VAR(ToDepth) * dy / D;
1225         czx = -2 * VAR(ToDepth) * dx / D;
1226#endif
1227      }
1228   }
1229   addlegbyname(fr, to, fToFirst, dx, dy, dz, vx, vy, vz
1230#ifndef NO_COVARIANCES
1231                , cxy, cyz, czx
1232#endif
1233                );
1234   return 1;
1235}
1236
1237static int
1238process_cartesian(prefix *fr, prefix *to, bool fToFirst)
1239{
1240   real dx = (VAL(Dx) * pcs->units[Q_DX] - pcs->z[Q_DX]) * pcs->sc[Q_DX];
1241   real dy = (VAL(Dy) * pcs->units[Q_DY] - pcs->z[Q_DY]) * pcs->sc[Q_DY];
1242   real dz = (VAL(Dz) * pcs->units[Q_DZ] - pcs->z[Q_DZ]) * pcs->sc[Q_DZ];
1243
1244   addlegbyname(fr, to, fToFirst, dx, dy, dz, VAR(Dx), VAR(Dy), VAR(Dz)
1245#ifndef NO_COVARIANCES
1246                , 0, 0, 0
1247#endif
1248                );
1249   return 1;
1250}
1251
1252static void
1253data_cartesian(void)
1254{
1255   prefix *fr = NULL, *to = NULL;
1256
1257   bool fMulti = fFalse;
1258
1259   reading first_stn = End;
1260
1261   reading *ordering;
1262
1263   again:
1264
1265   for (ordering = pcs->ordering ; ; ordering++) {
1266      skipblanks();
1267      switch (*ordering) {
1268       case Fr:
1269         fr = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1270         if (first_stn == End) first_stn = Fr;
1271         break;
1272       case To:
1273         to = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1274         if (first_stn == End) first_stn = To;
1275         break;
1276       case Station:
1277         fr = to;
1278         to = read_prefix(PFX_STATION);
1279         first_stn = To;
1280         break;
1281       case Dx: case Dy: case Dz:
1282         read_reading(*ordering, fFalse);
1283         break;
1284       case Ignore:
1285         skipword(); break;
1286       case IgnoreAllAndNewLine:
1287         skipline();
1288         /* fall through */
1289       case Newline:
1290         if (fr != NULL) {
1291            if (!process_cartesian(fr, to, first_stn == To))
1292               skipline();
1293         }
1294         fMulti = fTrue;
1295         while (1) {
1296            process_eol();
1297            process_bol();
1298            if (isData(ch)) break;
1299            if (!isComm(ch)) {
1300               push_back(ch);
1301               return;
1302            }
1303         }
1304         break;
1305       case IgnoreAll:
1306         skipline();
1307         /* fall through */
1308       case End:
1309         if (!fMulti) {
1310            process_cartesian(fr, to, first_stn == To);
1311            process_eol();
1312            return;
1313         }
1314         do {
1315            process_eol();
1316            process_bol();
1317         } while (isComm(ch));
1318         goto again;
1319       default: BUG("Unknown reading in ordering");
1320      }
1321   }
1322}
1323
1324static int
1325process_cylpolar(prefix *fr, prefix *to, bool fToFirst, bool fDepthChange)
1326{
1327   real tape = VAL(Tape);
1328
1329   real dx, dy, dz;
1330   real vx, vy, vz;
1331#ifndef NO_COVARIANCES
1332   real cxy = 0;
1333#endif
1334
1335   handle_comp_units();
1336
1337   /* depth gauge readings increase upwards with default calibration */
1338   if (fDepthChange) {
1339      SVX_ASSERT(VAL(FrDepth) == 0.0);
1340      dz = VAL(ToDepth) * pcs->units[Q_DEPTH] - pcs->z[Q_DEPTH];
1341      dz *= pcs->sc[Q_DEPTH];
1342   } else {
1343      dz = VAL(ToDepth) - VAL(FrDepth);
1344      dz *= pcs->units[Q_DEPTH] * pcs->sc[Q_DEPTH];
1345   }
1346
1347   /* adjusted tape is negative -- probably the calibration is wrong */
1348   if (tape < (real)0.0) {
1349      compile_warning(/*Negative adjusted tape reading*/79);
1350   }
1351
1352   if (VAL(Comp) == HUGE_REAL && VAL(BackComp) == HUGE_REAL) {
1353      /* plumb */
1354      dx = dy = (real)0.0;
1355      vx = vy = var(Q_POS) / 3.0 + dz * dz * var(Q_PLUMB);
1356      /* FIXME: Should use FrDepth sometimes... */
1357      vz = var(Q_POS) / 3.0 + 2 * VAR(ToDepth);
1358   } else {
1359      real sinB, cosB;
1360      real var_comp;
1361      real comp = handle_compass(&var_comp);
1362      sinB = sin(comp);
1363      cosB = cos(comp);
1364
1365      dx = tape * sinB;
1366      dy = tape * cosB;
1367
1368      vx = var(Q_POS) / 3.0 +
1369         VAR(Tape) * sinB * sinB + var_comp * dy * dy;
1370      vy = var(Q_POS) / 3.0 +
1371         VAR(Tape) * cosB * cosB + var_comp * dx * dx;
1372      /* FIXME: Should use FrDepth sometimes... */
1373      vz = var(Q_POS) / 3.0 + 2 * VAR(ToDepth);
1374
1375#ifndef NO_COVARIANCES
1376      cxy = (VAR(Tape) - var_comp * tape * tape) * sinB * cosB;
1377#endif
1378   }
1379   addlegbyname(fr, to, fToFirst, dx, dy, dz, vx, vy, vz
1380#ifndef NO_COVARIANCES
1381                , cxy, 0, 0
1382#endif
1383                );
1384   return 1;
1385}
1386
1387/* Process tape/compass/clino, diving, and cylpolar styles of survey data
1388 * Also handles topofil (fromcount/tocount or count) in place of tape */
1389static void
1390data_normal(void)
1391{
1392   prefix *fr = NULL, *to = NULL;
1393   reading first_stn = End;
1394
1395   bool fTopofil = fFalse, fMulti = fFalse;
1396   bool fRev;
1397   clino_type ctype, backctype;
1398   bool fDepthChange;
1399   unsigned long compass_dat_flags = 0;
1400
1401   reading *ordering;
1402
1403   VAL(Tape) = 0;
1404   VAL(Comp) = VAL(BackComp) = HUGE_REAL;
1405   VAL(FrCount) = VAL(ToCount) = 0;
1406   VAL(FrDepth) = VAL(ToDepth) = 0;
1407   VAL(Left) = VAL(Right) = VAL(Up) = VAL(Down) = HUGE_REAL;
1408
1409   fRev = fFalse;
1410   ctype = backctype = CTYPE_OMIT;
1411   fDepthChange = fFalse;
1412
1413   /* ordering may omit clino reading, so set up default here */
1414   /* this is also used if clino reading is the omit character */
1415   VAL(Clino) = VAL(BackClino) = 0;
1416
1417   again:
1418
1419   /* We clear these flags in the normal course of events, but if there's an
1420    * error in a reading, we might not, so make sure it has been cleared here.
1421    */
1422   pcs->flags &= ~(BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY));
1423   for (ordering = pcs->ordering; ; ordering++) {
1424      skipblanks();
1425      switch (*ordering) {
1426       case Fr:
1427          fr = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_ANON);
1428          if (first_stn == End) first_stn = Fr;
1429          break;
1430       case To:
1431          to = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_ANON);
1432          if (first_stn == End) first_stn = To;
1433          break;
1434       case Station:
1435          fr = to;
1436          to = read_prefix(PFX_STATION);
1437          first_stn = To;
1438          break;
1439       case Dir: {
1440          typedef enum {
1441             DIR_NULL=-1, DIR_FORE, DIR_BACK
1442          } dir_tok;
1443          static sztok dir_tab[] = {
1444             {"B",     DIR_BACK},
1445             {"F",     DIR_FORE},
1446          };
1447          dir_tok tok;
1448          get_token();
1449          tok = match_tok(dir_tab, TABSIZE(dir_tab));
1450          switch (tok) {
1451           case DIR_FORE:
1452             break;
1453           case DIR_BACK:
1454             fRev = fTrue;
1455             break;
1456           default:
1457             file.lpos += strlen(buffer);
1458             compile_error_skip(-/*Found “%s”, expecting “F” or “B”*/131,
1459                                buffer);
1460             process_eol();
1461             return;
1462          }
1463          break;
1464       }
1465       case Tape:
1466          read_reading(Tape, fFalse);
1467          if (VAL(Tape) < (real)0.0)
1468             compile_warning(-/*Negative tape reading*/60);
1469          break;
1470       case Count:
1471          VAL(FrCount) = VAL(ToCount);
1472          read_reading(ToCount, fFalse);
1473          fTopofil = fTrue;
1474          break;
1475       case FrCount:
1476          read_reading(FrCount, fFalse);
1477          break;
1478       case ToCount:
1479          read_reading(ToCount, fFalse);
1480          fTopofil = fTrue;
1481          break;
1482       case Comp: case BackComp:
1483          read_bearing_or_omit(*ordering);
1484          break;
1485       case Clino: case BackClino: {
1486          reading r = *ordering;
1487          clino_type * p_ctype = (r == Clino ? &ctype : &backctype);
1488          read_reading(r, fTrue);
1489          if (VAL(r) == HUGE_REAL) {
1490             VAL(r) = handle_plumb(p_ctype);
1491             if (VAL(r) != HUGE_REAL) break;
1492             compile_error_token(-/*Expecting numeric field, found “%s”*/9);
1493             skipline();
1494             process_eol();
1495             return;
1496          }
1497          *p_ctype = CTYPE_READING;
1498          break;
1499       }
1500       case FrDepth: case ToDepth:
1501          read_reading(*ordering, fFalse);
1502          break;
1503       case Depth:
1504          VAL(FrDepth) = VAL(ToDepth);
1505          read_reading(ToDepth, fFalse);
1506          break;
1507       case DepthChange:
1508          fDepthChange = fTrue;
1509          VAL(FrDepth) = 0;
1510          read_reading(ToDepth, fFalse);
1511          break;
1512       case CompassDATComp:
1513          read_bearing_or_omit(Comp);
1514          if (is_compass_NaN(VAL(Comp))) VAL(Comp) = HUGE_REAL;
1515          break;
1516       case CompassDATBackComp:
1517          read_bearing_or_omit(BackComp);
1518          if (is_compass_NaN(VAL(BackComp))) VAL(BackComp) = HUGE_REAL;
1519          break;
1520       case CompassDATClino: case CompassDATBackClino: {
1521          reading r;
1522          clino_type * p_ctype;
1523          if (*ordering == CompassDATClino) {
1524             r = Clino;
1525             p_ctype = &ctype;
1526          } else {
1527             r = BackClino;
1528             p_ctype = &backctype;
1529          }
1530          read_reading(r, fFalse);
1531          if (is_compass_NaN(VAL(r))) {
1532             VAL(r) = HUGE_REAL;
1533             *p_ctype = CTYPE_OMIT;
1534          } else {
1535             *p_ctype = CTYPE_READING;
1536          }
1537          break;
1538       }
1539       case CompassDATLeft: case CompassDATRight:
1540       case CompassDATUp: case CompassDATDown: {
1541          /* FIXME: need to actually make use of these entries! */
1542          reading actual = Left + (*ordering - CompassDATLeft);
1543          read_reading(actual, fFalse);
1544          if (VAL(actual) < 0) VAL(actual) = HUGE_REAL;
1545          break;
1546       }
1547       case CompassDATFlags:
1548          if (ch == '#') {
1549             nextch();
1550             if (ch == '|') {
1551                filepos fp;
1552                get_pos(&fp);
1553                nextch();
1554                while (ch >= 'A' && ch <= 'Z') {
1555                   compass_dat_flags |= BIT(ch - 'A');
1556                   /* FIXME: we currently understand:
1557                    *   L (exclude from length)
1558                    *   X (exclude data)
1559                    * but should also handle at least some of:
1560                    *   C (no adjustment)
1561                    *   P (no plot)
1562                    */
1563                   nextch();
1564                }
1565                if (ch == '#') {
1566                   nextch();
1567                } else {
1568                   compass_dat_flags = 0;
1569                   set_pos(&fp);
1570                   push_back('|');
1571                   ch = '#';
1572                }
1573             } else {
1574                push_back(ch);
1575                ch = '#';
1576             }
1577          }
1578          break;
1579       case Ignore:
1580          skipword(); break;
1581       case IgnoreAllAndNewLine:
1582          skipline();
1583          /* fall through */
1584       case Newline:
1585          if (fr != NULL) {
1586             int r;
1587             int save_flags;
1588             int implicit_splay;
1589             if (fTopofil)
1590                VAL(Tape) = VAL(ToCount) - VAL(FrCount);
1591             /* Note: frdepth == todepth test works regardless of fDepthChange
1592              * (frdepth always zero, todepth is change of depth) and also
1593              * works for STYLE_NORMAL (both remain 0) */
1594             if (TSTBIT(pcs->infer, INFER_EQUATES) &&
1595                 VAL(Tape) == (real)0.0 && VAL(FrDepth) == VAL(ToDepth)) {
1596                process_equate(fr, to);
1597                goto inferred_equate;
1598             }
1599             if (fRev) {
1600                prefix *t = fr;
1601                fr = to;
1602                to = t;
1603             }
1604             if (fTopofil) {
1605                VAL(Tape) *= pcs->units[Q_COUNT] * pcs->sc[Q_COUNT];
1606             } else {
1607                VAL(Tape) *= pcs->units[Q_LENGTH];
1608                VAL(Tape) -= pcs->z[Q_LENGTH];
1609                VAL(Tape) *= pcs->sc[Q_LENGTH];
1610             }
1611             implicit_splay = TSTBIT(pcs->flags, FLAGS_IMPLICIT_SPLAY);
1612             pcs->flags &= ~(BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY));
1613             save_flags = pcs->flags;
1614             if (implicit_splay) {
1615                pcs->flags |= BIT(FLAGS_SPLAY);
1616             }
1617             switch (pcs->style) {
1618              case STYLE_NORMAL:
1619                r = process_normal(fr, to, (first_stn == To) ^ fRev,
1620                                   ctype, backctype);
1621                break;
1622              case STYLE_DIVING:
1623                r = process_diving(fr, to, (first_stn == To) ^ fRev,
1624                                   fDepthChange);
1625                break;
1626              case STYLE_CYLPOLAR:
1627                r = process_cylpolar(fr, to, (first_stn == To) ^ fRev,
1628                                     fDepthChange);
1629                break;
1630              default:
1631                r = 0; /* avoid warning */
1632                BUG("bad style");
1633             }
1634             pcs->flags = save_flags;
1635             if (!r) skipline();
1636
1637             /* Swap fr and to back to how they were for next line */
1638             if (fRev) {
1639                prefix *t = fr;
1640                fr = to;
1641                to = t;
1642             }
1643          }
1644
1645          fRev = fFalse;
1646          ctype = backctype = CTYPE_OMIT;
1647          fDepthChange = fFalse;
1648
1649          /* ordering may omit clino reading, so set up default here */
1650          /* this is also used if clino reading is the omit character */
1651          VAL(Clino) = VAL(BackClino) = 0;
1652
1653          inferred_equate:
1654
1655          fMulti = fTrue;
1656          while (1) {
1657              process_eol();
1658              process_bol();
1659              if (isData(ch)) break;
1660              if (!isComm(ch)) {
1661                 push_back(ch);
1662                 return;
1663              }
1664          }
1665          break;
1666       case IgnoreAll:
1667          skipline();
1668          /* fall through */
1669       case End:
1670          if (!fMulti) {
1671             int save_flags;
1672             int implicit_splay;
1673             /* Compass ignore flag is 'X' */
1674             if ((compass_dat_flags & BIT('X' - 'A'))) {
1675                process_eol();
1676                return;
1677             }
1678             if (fRev) {
1679                prefix *t = fr;
1680                fr = to;
1681                to = t;
1682             }
1683             if (fTopofil) VAL(Tape) = VAL(ToCount) - VAL(FrCount);
1684             /* Note: frdepth == todepth test works regardless of fDepthChange
1685              * (frdepth always zero, todepth is change of depth) and also
1686              * works for STYLE_NORMAL (both remain 0) */
1687             if (TSTBIT(pcs->infer, INFER_EQUATES) &&
1688                 VAL(Tape) == (real)0.0 && VAL(FrDepth) == VAL(ToDepth)) {
1689                process_equate(fr, to);
1690                process_eol();
1691                return;
1692             }
1693             if (fTopofil) {
1694                VAL(Tape) *= pcs->units[Q_COUNT] * pcs->sc[Q_COUNT];
1695             } else {
1696                VAL(Tape) *= pcs->units[Q_LENGTH];
1697                VAL(Tape) -= pcs->z[Q_LENGTH];
1698                VAL(Tape) *= pcs->sc[Q_LENGTH];
1699             }
1700             implicit_splay = TSTBIT(pcs->flags, FLAGS_IMPLICIT_SPLAY);
1701             pcs->flags &= ~(BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY));
1702             save_flags = pcs->flags;
1703             if (implicit_splay) {
1704                pcs->flags |= BIT(FLAGS_SPLAY);
1705             }
1706             if ((compass_dat_flags & BIT('L' - 'A'))) {
1707                /* 'L' means "exclude from length" - map this to Survex's
1708                 * FLAGS_DUPLICATE. */
1709                pcs->flags |= BIT(FLAGS_DUPLICATE);
1710             }
1711             switch (pcs->style) {
1712              case STYLE_NORMAL:
1713                process_normal(fr, to, (first_stn == To) ^ fRev,
1714                               ctype, backctype);
1715                break;
1716              case STYLE_DIVING:
1717                process_diving(fr, to, (first_stn == To) ^ fRev,
1718                               fDepthChange);
1719                break;
1720              case STYLE_CYLPOLAR:
1721                process_cylpolar(fr, to, (first_stn == To) ^ fRev,
1722                                 fDepthChange);
1723                break;
1724              default:
1725                BUG("bad style");
1726             }
1727             pcs->flags = save_flags;
1728
1729             process_eol();
1730             return;
1731          }
1732          do {
1733             process_eol();
1734             process_bol();
1735          } while (isComm(ch));
1736          goto again;
1737       default:
1738          BUG("Unknown reading in ordering");
1739      }
1740   }
1741}
1742
1743static int
1744process_lrud(prefix *stn)
1745{
1746   SVX_ASSERT(next_lrud);
1747   lrud * xsect = osnew(lrud);
1748   xsect->stn = stn;
1749   xsect->l = (VAL(Left) * pcs->units[Q_LEFT] - pcs->z[Q_LEFT]) * pcs->sc[Q_LEFT];
1750   xsect->r = (VAL(Right) * pcs->units[Q_RIGHT] - pcs->z[Q_RIGHT]) * pcs->sc[Q_RIGHT];
1751   xsect->u = (VAL(Up) * pcs->units[Q_UP] - pcs->z[Q_UP]) * pcs->sc[Q_UP];
1752   xsect->d = (VAL(Down) * pcs->units[Q_DOWN] - pcs->z[Q_DOWN]) * pcs->sc[Q_DOWN];
1753   xsect->meta = pcs->meta;
1754   if (pcs->meta) ++pcs->meta->ref_count;
1755   xsect->next = NULL;
1756   *next_lrud = xsect;
1757   next_lrud = &(xsect->next);
1758
1759   return 1;
1760}
1761
1762static void
1763data_passage(void)
1764{
1765   prefix *stn = NULL;
1766   reading *ordering;
1767
1768   for (ordering = pcs->ordering ; ; ordering++) {
1769      skipblanks();
1770      switch (*ordering) {
1771       case Station:
1772         stn = read_prefix(PFX_STATION);
1773         break;
1774       case Left: case Right: case Up: case Down:
1775         read_reading(*ordering, fTrue);
1776         if (VAL(*ordering) == HUGE_REAL) {
1777            if (!isOmit(ch)) {
1778               compile_error_token(-/*Expecting numeric field, found “%s”*/9);
1779            } else {
1780               nextch();
1781            }
1782            VAL(*ordering) = -1;
1783         }
1784         break;
1785       case Ignore:
1786         skipword(); break;
1787       case IgnoreAll:
1788         skipline();
1789         /* fall through */
1790       case End: {
1791         process_lrud(stn);
1792         process_eol();
1793         return;
1794       }
1795       default: BUG("Unknown reading in ordering");
1796      }
1797   }
1798}
1799
1800static int
1801process_nosurvey(prefix *fr, prefix *to, bool fToFirst)
1802{
1803   nosurveylink *link;
1804
1805   /* Suppress "unused fixed point" warnings for these stations */
1806   fr->sflags |= BIT(SFLAGS_USED);
1807   to->sflags |= BIT(SFLAGS_USED);
1808
1809   /* add to linked list which is dealt with after network is solved */
1810   link = osnew(nosurveylink);
1811   if (fToFirst) {
1812      link->to = StnFromPfx(to);
1813      link->fr = StnFromPfx(fr);
1814   } else {
1815      link->fr = StnFromPfx(fr);
1816      link->to = StnFromPfx(to);
1817   }
1818   link->flags = pcs->flags | (STYLE_NOSURVEY << FLAGS_STYLE_BIT0);
1819   link->meta = pcs->meta;
1820   if (pcs->meta) ++pcs->meta->ref_count;
1821   link->next = nosurveyhead;
1822   nosurveyhead = link;
1823   return 1;
1824}
1825
1826static void
1827data_nosurvey(void)
1828{
1829   prefix *fr = NULL, *to = NULL;
1830
1831   bool fMulti = fFalse;
1832
1833   reading first_stn = End;
1834
1835   reading *ordering;
1836
1837   again:
1838
1839   for (ordering = pcs->ordering ; ; ordering++) {
1840      skipblanks();
1841      switch (*ordering) {
1842       case Fr:
1843          fr = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1844          if (first_stn == End) first_stn = Fr;
1845          break;
1846       case To:
1847          to = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1848          if (first_stn == End) first_stn = To;
1849          break;
1850       case Station:
1851          fr = to;
1852          to = read_prefix(PFX_STATION);
1853          first_stn = To;
1854          break;
1855       case Ignore:
1856         skipword(); break;
1857       case IgnoreAllAndNewLine:
1858         skipline();
1859         /* fall through */
1860       case Newline:
1861         if (fr != NULL) {
1862            if (!process_nosurvey(fr, to, first_stn == To))
1863               skipline();
1864         }
1865         if (ordering[1] == End) {
1866            do {
1867               process_eol();
1868               process_bol();
1869            } while (isComm(ch));
1870            if (!isData(ch)) {
1871               push_back(ch);
1872               return;
1873            }
1874            goto again;
1875         }
1876         fMulti = fTrue;
1877         while (1) {
1878            process_eol();
1879            process_bol();
1880            if (isData(ch)) break;
1881            if (!isComm(ch)) {
1882               push_back(ch);
1883               return;
1884            }
1885         }
1886         break;
1887       case IgnoreAll:
1888         skipline();
1889         /* fall through */
1890       case End:
1891         if (!fMulti) {
1892            (void)process_nosurvey(fr, to, first_stn == To);
1893            process_eol();
1894            return;
1895         }
1896         do {
1897            process_eol();
1898            process_bol();
1899         } while (isComm(ch));
1900         goto again;
1901       default: BUG("Unknown reading in ordering");
1902      }
1903   }
1904}
1905
1906/* totally ignore a line of survey data */
1907static void
1908data_ignore(void)
1909{
1910   skipline();
1911   process_eol();
1912}
Note: See TracBrowser for help on using the repository browser.