source: git/src/datain.c @ 4f70ebc

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

src/: Track the data style of each leg, and pass it in to img - it's
not yet stored in the .3d file, but now it is easily available so it
can be.

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