source: git/src/datain.c @ 5dc0378

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

src/datain.c: Fix NULL pointer dereference when processing Compass
DAT file without 'SURVEY DATE:'.

  • 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,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    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         copy_on_write_meta(pcs);
508         if (ch == ':') {
509             int year, month, day;
510
511             nextch();
512
513             month = read_uint();
514             day = read_uint();
515             year = read_uint();
516             /* Note: Larry says a 2 digit year is always 19XX */
517             if (year < 100) year += 1900;
518
519             pcs->meta->days1 = pcs->meta->days2 = days_since_1900(year, month, day);
520         } else {
521             pcs->meta->days1 = pcs->meta->days2 = -1;
522         }
523         skipline();
524         process_eol();
525         /* SURVEY TEAM: */
526         get_token();
527         get_token();
528         skipline();
529         process_eol();
530         /* <Survey team> */
531         nextch();
532         skipline();
533         process_eol();
534         /* DECLINATION: 1.00  FORMAT: DDDDLUDRADLN  CORRECTIONS: 2.00 3.00 4.00 */
535         get_token();
536         nextch(); /* : */
537         skipblanks();
538         pcs->z[Q_DECLINATION] = -read_numeric(fFalse, NULL);
539         pcs->z[Q_DECLINATION] *= pcs->units[Q_DECLINATION];
540         get_token();
541         pcs->ordering = compass_order;
542         if (strcmp(buffer, "FORMAT") == 0) {
543            nextch(); /* : */
544            get_token();
545            if (strlen(buffer) >= 12 && buffer[11] == 'B') {
546               /* We have backsights for compass and clino */
547               pcs->ordering = compass_order_backsights;
548            }
549            get_token();
550         }
551         if (strcmp(buffer, "CORRECTIONS") == 0) {
552            nextch(); /* : */
553            pcs->z[Q_BEARING] = -rad(read_numeric(fFalse, NULL));
554            pcs->z[Q_GRADIENT] = -rad(read_numeric(fFalse, NULL));
555            pcs->z[Q_LENGTH] = -read_numeric(fFalse, NULL);
556         } else {
557            pcs->z[Q_BEARING] = 0;
558            pcs->z[Q_GRADIENT] = 0;
559            pcs->z[Q_LENGTH] = 0;
560         }
561         skipline();
562         process_eol();
563         /* BLANK LINE */
564         process_bol();
565         skipline();
566         process_eol();
567         /* heading line */
568         process_bol();
569         skipline();
570         process_eol();
571         /* BLANK LINE */
572         process_bol();
573         skipline();
574         process_eol();
575         while (!feof(file.fh)) {
576            process_bol();
577            if (ch == '\x0c') {
578               nextch();
579               process_eol();
580               break;
581            }
582            data_normal();
583         }
584      }
585      {
586         settings *pcsParent = pcs->next;
587         SVX_ASSERT(pcsParent);
588         pcs->ordering = NULL;
589         free_settings(pcs);
590         pcs = pcsParent;
591      }
592   } else if (fmt == FMT_MAK) {
593      nextch_handling_eol();
594      while (!feof(file.fh) && !ferror(file.fh)) {
595         if (ch == '#') {
596            /* include a file */
597            int ch_store;
598            char *dat_pth = path_from_fnm(file.filename);
599            char *dat_fnm = NULL;
600            int dat_fnm_len;
601            nextch_handling_eol();
602            while (ch != ',' && ch != ';' && ch != EOF) {
603               while (isEol(ch)) process_eol();
604               s_catchar(&dat_fnm, &dat_fnm_len, (char)ch);
605               nextch_handling_eol();
606            }
607            while (ch != ';' && ch != EOF) {
608               prefix *name;
609               nextch_handling_eol();
610               name = read_prefix(PFX_STATION|PFX_OPT);
611               if (name) {
612                  skipblanks();
613                  if (ch == '[') {
614                     /* fixed pt */
615                     node *stn;
616                     real x, y, z;
617                     name->sflags |= BIT(SFLAGS_FIXED);
618                     nextch_handling_eol();
619                     while (!isdigit(ch) && ch != '+' && ch != '-' &&
620                            ch != '.' && ch != ']' && ch != EOF) {
621                        nextch_handling_eol();
622                     }
623                     x = read_numeric(fFalse, NULL);
624                     while (!isdigit(ch) && ch != '+' && ch != '-' &&
625                            ch != '.' && ch != ']' && ch != EOF) {
626                        nextch_handling_eol();
627                     }
628                     y = read_numeric(fFalse, NULL);
629                     while (!isdigit(ch) && ch != '+' && ch != '-' &&
630                            ch != '.' && ch != ']' && ch != EOF) {
631                        nextch_handling_eol();
632                     }
633                     z = read_numeric(fFalse, NULL);
634                     stn = StnFromPfx(name);
635                     if (!fixed(stn)) {
636                        POS(stn, 0) = x;
637                        POS(stn, 1) = y;
638                        POS(stn, 2) = z;
639                        fix(stn);
640                     } else {
641                        if (x != POS(stn, 0) || y != POS(stn, 1) ||
642                            z != POS(stn, 2)) {
643                           compile_error(/*Station already fixed or equated to a fixed point*/46);
644                        } else {
645                           compile_warning(/*Station already fixed at the same coordinates*/55);
646                        }
647                     }
648                     while (ch != ']' && ch != EOF) nextch_handling_eol();
649                     if (ch == ']') {
650                        nextch_handling_eol();
651                        skipblanks();
652                     }
653                  } else {
654                     /* FIXME: link station - ignore for now */
655                     /* FIXME: perhaps issue warning? */
656                  }
657                  while (ch != ',' && ch != ';' && ch != EOF)
658                     nextch_handling_eol();
659               }
660            }
661            if (dat_fnm) {
662               ch_store = ch;
663               data_file(dat_pth, dat_fnm);
664               ch = ch_store;
665               osfree(dat_fnm);
666            }
667         } else {
668            /* FIXME: also check for % and $ later */
669            nextch_handling_eol();
670         }
671      }
672      {
673         settings *pcsParent = pcs->next;
674         SVX_ASSERT(pcsParent);
675         free_settings(pcs);
676         pcs = pcsParent;
677      }
678   } else {
679      while (!feof(file.fh) && !ferror(file.fh)) {
680         if (!process_non_data_line()) {
681            f_export_ok = fFalse;
682            switch (pcs->style) {
683             case STYLE_NORMAL:
684             case STYLE_DIVING:
685             case STYLE_CYLPOLAR:
686               data_normal();
687               break;
688             case STYLE_CARTESIAN:
689               data_cartesian();
690               break;
691             case STYLE_PASSAGE:
692               data_passage();
693               break;
694             case STYLE_NOSURVEY:
695               data_nosurvey();
696               break;
697             case STYLE_IGNORE:
698               data_ignore();
699               break;
700             default:
701               BUG("bad style");
702            }
703         }
704      }
705   }
706
707   /* don't allow *BEGIN at the end of a file, then *EXPORT in the
708    * including file */
709   f_export_ok = fFalse;
710
711#ifndef NO_PERCENTAGE
712   if (fPercent) putnl();
713#endif
714
715   if (pcs->begin_lineno) {
716      error_in_file(file.filename, pcs->begin_lineno,
717                    /*BEGIN with no matching END in this file*/23);
718      /* Implicitly close any unclosed BEGINs from this file */
719      do {
720         settings *pcsParent = pcs->next;
721         SVX_ASSERT(pcsParent);
722         free_settings(pcs);
723         pcs = pcsParent;
724      } while (pcs->begin_lineno);
725   }
726
727   pcs->begin_lineno = begin_lineno_store;
728
729   if (ferror(file.fh))
730      fatalerror_in_file(file.filename, 0, /*Error reading file*/18);
731
732   (void)fclose(file.fh);
733
734   file = file_store;
735
736   /* don't free this - it may be pointed to by prefix.file */
737   /* osfree(file.filename); */
738}
739
740static real
741mod2pi(real a)
742{
743   return a - floor(a / (2 * M_PI)) * (2 * M_PI);
744}
745
746static real
747handle_plumb(clino_type *p_ctype)
748{
749   typedef enum {
750      CLINO_NULL=-1, CLINO_UP, CLINO_DOWN, CLINO_LEVEL
751   } clino_tok;
752   static sztok clino_tab[] = {
753      {"D",     CLINO_DOWN},
754      {"DOWN",  CLINO_DOWN},
755      {"H",     CLINO_LEVEL},
756      {"LEVEL", CLINO_LEVEL},
757      {"U",     CLINO_UP},
758      {"UP",    CLINO_UP},
759      {NULL,    CLINO_NULL}
760   };
761   static real clinos[] = {(real)M_PI_2, (real)(-M_PI_2), (real)0.0};
762   clino_tok tok;
763
764   skipblanks();
765   if (isalpha(ch)) {
766      filepos fp;
767      get_pos(&fp);
768      get_token();
769      tok = match_tok(clino_tab, TABSIZE(clino_tab));
770      if (tok != CLINO_NULL) {
771         *p_ctype = (tok == CLINO_LEVEL ? CTYPE_HORIZ : CTYPE_PLUMB);
772         return clinos[tok];
773      }
774      set_pos(&fp);
775   } else if (isSign(ch)) {
776      int chOld = ch;
777      nextch();
778      if (toupper(ch) == 'V') {
779         nextch();
780         *p_ctype = CTYPE_PLUMB;
781         return (!isMinus(chOld) ? M_PI_2 : -M_PI_2);
782      }
783
784      if (isOmit(chOld)) {
785         *p_ctype = CTYPE_OMIT;
786         /* no clino reading, so assume 0 with large sd */
787         return (real)0.0;
788      }
789   } else if (isOmit(ch)) {
790      /* OMIT char may not be a SIGN char too so we need to check here as
791       * well as above... */
792      nextch();
793      *p_ctype = CTYPE_OMIT;
794      /* no clino reading, so assume 0 with large sd */
795      return (real)0.0;
796   }
797   return HUGE_REAL;
798}
799
800static void
801warn_readings_differ(int msgno, real diff)
802{
803   char buf[64];
804   char *p;
805   sprintf(buf, "%.2f", deg(fabs(diff)));
806   p = strchr(buf, '.');
807   if (p) {
808      char *z = p;
809      while (*++p) {
810         if (*p != '0') z = p + 1;
811      }
812      if (*z) *z = '\0';
813   }
814   compile_warning(msgno, buf);
815}
816
817static bool
818handle_comp_units(void)
819{
820   bool fNoComp = fTrue;
821   if (VAL(Comp) != HUGE_REAL) {
822      fNoComp = fFalse;
823      VAL(Comp) *= pcs->units[Q_BEARING];
824      if (VAL(Comp) < (real)0.0 || VAL(Comp) - M_PI * 2.0 > EPSILON) {
825         compile_warning(/*Suspicious compass reading*/59);
826         VAL(Comp) = mod2pi(VAL(Comp));
827      }
828   }
829   if (VAL(BackComp) != HUGE_REAL) {
830      fNoComp = fFalse;
831      VAL(BackComp) *= pcs->units[Q_BACKBEARING];
832      if (VAL(BackComp) < (real)0.0 || VAL(BackComp) - M_PI * 2.0 > EPSILON) {
833         /* FIXME: different message for BackComp? */
834         compile_warning(/*Suspicious compass reading*/59);
835         VAL(BackComp) = mod2pi(VAL(BackComp));
836      }
837   }
838   return fNoComp;
839}
840
841static real
842handle_compass(real *p_var)
843{
844   real compvar = VAR(Comp);
845   real comp = VAL(Comp);
846   real backcomp = VAL(BackComp);
847   if (comp != HUGE_REAL) {
848      comp = (comp - pcs->z[Q_BEARING]) * pcs->sc[Q_BEARING];
849      comp -= pcs->z[Q_DECLINATION];
850   }
851   if (backcomp != HUGE_REAL) {
852      backcomp = (backcomp - pcs->z[Q_BACKBEARING])
853              * pcs->sc[Q_BACKBEARING];
854      backcomp -= pcs->z[Q_DECLINATION];
855      backcomp -= M_PI;
856      if (comp != HUGE_REAL) {
857         real diff = comp - backcomp;
858         real adj = fabs(diff) > M_PI ? M_PI : 0;
859         diff -= floor((diff + M_PI) / (2 * M_PI)) * 2 * M_PI;
860         if (sqrd(diff / 2.0) > compvar + VAR(Q_BACKBEARING)) {
861            /* fore and back readings differ by more than 2 sds */
862            warn_readings_differ(/*COMPASS reading and BACKCOMPASS reading disagree by %s degrees*/98, diff);
863         }
864         comp = (comp / compvar + backcomp / VAR(BackComp));
865         compvar = (compvar + VAR(BackComp)) / 4;
866         comp *= compvar;
867         comp += adj;
868      } else {
869         comp = backcomp;
870         compvar = VAR(BackComp);
871      }
872   }
873   *p_var = compvar;
874   return comp;
875}
876
877static int
878process_normal(prefix *fr, prefix *to, bool fToFirst,
879               clino_type ctype, clino_type backctype)
880{
881   real tape = VAL(Tape);
882   real clin = VAL(Clino);
883   real backclin = VAL(BackClino);
884
885   real dx, dy, dz;
886   real vx, vy, vz;
887#ifndef NO_COVARIANCES
888   real cxy, cyz, czx;
889#endif
890
891   bool fNoComp;
892
893   /* adjusted tape is negative -- probably the calibration is wrong */
894   if (tape < (real)0.0) {
895      /* TRANSLATE different message for topofil? */
896      compile_warning(/*Negative adjusted tape reading*/79);
897   }
898
899   fNoComp = handle_comp_units();
900
901   if (ctype == CTYPE_READING) {
902      bool range_0_180;
903      real z;
904      real diff_from_abs90;
905      clin *= pcs->units[Q_GRADIENT];
906      /* percentage scale */
907      if (pcs->f_clino_percent) clin = atan(clin);
908      /* We want to warn if there's a reading which it would be impossible
909       * to have read from the instrument (e.g. on a -90 to 90 degree scale
910       * you can't read "96" (it's probably a typo for "69").  However, the
911       * gradient reading from a topofil is typically in the range 0 to 180,
912       * with 90 being horizontal.
913       *
914       * Really we should allow the valid range to be specified, but for now
915       * we infer it from the zero error - if this is within 45 degrees of
916       * 90 then we assume the range is 0 to 180.
917       */
918      z = pcs->z[Q_GRADIENT];
919      range_0_180 = (z > M_PI_4 && z < 3*M_PI_4);
920      diff_from_abs90 = fabs(clin) - M_PI_2;
921      if (diff_from_abs90 > EPSILON) {
922         if (!range_0_180)
923            compile_warning(/*Clino reading over 90 degrees (absolute value)*/51);
924      } else if (TSTBIT(pcs->infer, INFER_PLUMBS) &&
925                 diff_from_abs90 >= -EPSILON) {
926         ctype = CTYPE_INFERPLUMB;
927      }
928      if (range_0_180 && ctype != CTYPE_INFERPLUMB) {
929         /* FIXME: Warning message not ideal... */
930         if (clin < 0.0 || clin - M_PI > EPSILON)
931            compile_warning(/*Clino reading over 90 degrees (absolute value)*/51);
932      }
933   }
934
935   if (backctype == CTYPE_READING) {
936      backclin *= pcs->units[Q_BACKGRADIENT];
937      /* percentage scale */
938      if (pcs->f_backclino_percent) backclin = atan(backclin);
939      if (ctype != CTYPE_READING) {
940         real diff_from_abs90 = fabs(backclin) - M_PI_2;
941         if (diff_from_abs90 > EPSILON) {
942            /* FIXME: different message for BackClino? */
943            compile_warning(/*Clino reading over 90 degrees (absolute value)*/51);
944         } else if (TSTBIT(pcs->infer, INFER_PLUMBS) &&
945                    diff_from_abs90 >= -EPSILON) {
946            backctype = CTYPE_INFERPLUMB;
947         }
948      }
949   }
950
951   /* un-infer the plumb if the backsight was just a reading */
952   if (ctype == CTYPE_INFERPLUMB && backctype == CTYPE_READING) {
953       ctype = CTYPE_READING;
954   }
955
956   if (ctype != CTYPE_OMIT && backctype != CTYPE_OMIT && ctype != backctype) {
957      compile_error_skip(/*CLINO and BACKCLINO readings must be of the same type*/84);
958      return 0;
959   }
960
961   if (ctype == CTYPE_PLUMB || ctype == CTYPE_INFERPLUMB ||
962       backctype == CTYPE_PLUMB || backctype == CTYPE_INFERPLUMB) {
963      /* plumbed */
964      if (!fNoComp) {
965         if (ctype == CTYPE_PLUMB ||
966             (ctype == CTYPE_INFERPLUMB && VAL(Comp) != 0.0) ||
967             backctype == CTYPE_PLUMB ||
968             (backctype == CTYPE_INFERPLUMB && VAL(BackComp) != 0.0)) {
969            /* FIXME: Different message for BackComp? */
970            compile_warning(/*Compass reading given on plumbed leg*/21);
971         }
972      }
973
974      dx = dy = (real)0.0;
975      if (ctype != CTYPE_OMIT) {
976         if (backctype != CTYPE_OMIT && (clin > 0) == (backclin > 0)) {
977            /* We've got two UPs or two DOWNs - FIXME: not ideal message */
978            compile_error_skip(/*CLINO and BACKCLINO readings must be of the same type*/84);
979            return 0;
980         }
981         dz = (clin > (real)0.0) ? tape : -tape;
982      } else {
983         dz = (backclin < (real)0.0) ? tape : -tape;
984      }
985      vx = vy = var(Q_POS) / 3.0 + dz * dz * var(Q_PLUMB);
986      vz = var(Q_POS) / 3.0 + VAR(Tape);
987#ifndef NO_COVARIANCES
988      /* Correct values - no covariances in this case! */
989      cxy = cyz = czx = (real)0.0;
990#endif
991   } else {
992      /* Each of ctype and backctype are either CTYPE_READING/CTYPE_HORIZ
993       * or CTYPE_OMIT */
994      /* clino */
995      real L2, cosG, LcosG, cosG2, sinB, cosB, dx2, dy2, dz2, v, V;
996      if (fNoComp) {
997         compile_error_skip(/*Compass reading may not be omitted except on plumbed legs*/14);
998         return 0;
999      }
1000      if (tape == (real)0.0) {
1001         dx = dy = dz = (real)0.0;
1002         vx = vy = vz = (real)(var(Q_POS) / 3.0); /* Position error only */
1003#ifndef NO_COVARIANCES
1004         cxy = cyz = czx = (real)0.0;
1005#endif
1006#if DEBUG_DATAIN_1
1007         printf("Zero length leg: vx = %f, vy = %f, vz = %f\n", vx, vy, vz);
1008#endif
1009      } else {
1010         real sinGcosG;
1011         /* take into account variance in LEVEL case */
1012         real var_clin = var(Q_LEVEL);
1013         real var_comp;
1014         real comp = handle_compass(&var_comp);
1015         /* ctype != CTYPE_READING is LEVEL case */
1016         if (ctype == CTYPE_READING) {
1017            clin = (clin - pcs->z[Q_GRADIENT]) * pcs->sc[Q_GRADIENT];
1018            var_clin = VAR(Clino);
1019         }
1020         if (backctype == CTYPE_READING) {
1021            backclin = (backclin - pcs->z[Q_BACKGRADIENT])
1022               * pcs->sc[Q_BACKGRADIENT];
1023            if (ctype == CTYPE_READING) {
1024               if (sqrd((clin + backclin) / 3.0) > var_clin + VAR(BackClino)) {
1025                  /* fore and back readings differ by more than 3 sds */
1026                  warn_readings_differ(/*CLINO reading and BACKCLINO reading disagree by %s degrees*/99, clin + backclin);
1027               }
1028               clin = (clin / var_clin - backclin / VAR(BackClino));
1029               var_clin = (var_clin + VAR(BackClino)) / 4;
1030               clin *= var_clin;
1031            } else {
1032               clin = -backclin;
1033               var_clin = VAR(BackClino);
1034            }
1035         }
1036
1037#if DEBUG_DATAIN
1038         printf("    %4.2f %4.2f %4.2f\n", tape, comp, clin);
1039#endif
1040         cosG = cos(clin);
1041         LcosG = tape * cosG;
1042         sinB = sin(comp);
1043         cosB = cos(comp);
1044#if DEBUG_DATAIN_1
1045         printf("sinB = %f, cosG = %f, LcosG = %f\n", sinB, cosG, LcosG);
1046#endif
1047         dx = LcosG * sinB;
1048         dy = LcosG * cosB;
1049         dz = tape * sin(clin);
1050/*      printf("%.2f\n",clin); */
1051#if DEBUG_DATAIN_1
1052         printf("dx = %f\ndy = %f\ndz = %f\n", dx, dy, dz);
1053#endif
1054         dx2 = dx * dx;
1055         L2 = tape * tape;
1056         V = VAR(Tape) / L2;
1057         dy2 = dy * dy;
1058         cosG2 = cosG * cosG;
1059         sinGcosG = sin(clin) * cosG;
1060         dz2 = dz * dz;
1061         v = dz2 * var_clin;
1062#ifdef NO_COVARIANCES
1063         vx = (var(Q_POS) / 3.0 + dx2 * V + dy2 * var_comp +
1064               (.5 + sinB * sinB * cosG2) * v);
1065         vy = (var(Q_POS) / 3.0 + dy2 * V + dx2 * var_comp +
1066               (.5 + cosB * cosB * cosG2) * v);
1067         if (ctype == CTYPE_OMIT && backctype == CTYPE_OMIT) {
1068            /* if no clino, assume sd=tape/sqrt(10) so 3sds = .95*tape */
1069            vz = var(Q_POS) / 3.0 + L2 * (real)0.1;
1070         } else {
1071            vz = var(Q_POS) / 3.0 + dz2 * V + L2 * cosG2 * var_clin;
1072         }
1073         /* for Surveyor87 errors: vx=vy=vz=var(Q_POS)/3.0; */
1074#else
1075         vx = var(Q_POS) / 3.0 + dx2 * V + dy2 * var_comp +
1076            (sinB * sinB * v);
1077         vy = var(Q_POS) / 3.0 + dy2 * V + dx2 * var_comp +
1078            (cosB * cosB * v);
1079         if (ctype == CTYPE_OMIT && backctype == CTYPE_OMIT) {
1080            /* if no clino, assume sd=tape/sqrt(10) so 3sds = .95*tape */
1081            vz = var(Q_POS) / 3.0 + L2 * (real)0.1;
1082         } else {
1083            vz = var(Q_POS) / 3.0 + dz2 * V + L2 * cosG2 * var_clin;
1084         }
1085         /* usual covariance formulae are fine in no clino case since
1086          * dz = 0 so value of var_clin is ignored */
1087         cxy = sinB * cosB * (VAR(Tape) * cosG2 + var_clin * dz2)
1088               - var_comp * dx * dy;
1089         czx = VAR(Tape) * sinB * sinGcosG - var_clin * dx * dz;
1090         cyz = VAR(Tape) * cosB * sinGcosG - var_clin * dy * dz;
1091#if 0
1092         printf("vx = %6.3f, vy = %6.3f, vz = %6.3f\n", vx, vy, vz);
1093         printf("cxy = %6.3f, cyz = %6.3f, czx = %6.3f\n", cxy, cyz, czx);
1094#endif
1095#endif
1096#if DEBUG_DATAIN_1
1097         printf("In DATAIN.C, vx = %f, vy = %f, vz = %f\n", vx, vy, vz);
1098#endif
1099      }
1100   }
1101#if DEBUG_DATAIN_1
1102   printf("Just before addleg, vx = %f\n", vx);
1103#endif
1104   /*printf("dx,dy,dz = %.2f %.2f %.2f\n\n", dx, dy, dz);*/
1105   addlegbyname(fr, to, fToFirst, dx, dy, dz, vx, vy, vz
1106#ifndef NO_COVARIANCES
1107                , cyz, czx, cxy
1108#endif
1109                );
1110   return 1;
1111}
1112
1113static int
1114process_diving(prefix *fr, prefix *to, bool fToFirst, bool fDepthChange)
1115{
1116   real tape = VAL(Tape);
1117
1118   real dx, dy, dz;
1119   real vx, vy, vz;
1120#ifndef NO_COVARIANCES
1121   real cxy = 0, cyz = 0, czx = 0;
1122#endif
1123
1124   handle_comp_units();
1125
1126   /* depth gauge readings increase upwards with default calibration */
1127   if (fDepthChange) {
1128      SVX_ASSERT(VAL(FrDepth) == 0.0);
1129      dz = VAL(ToDepth) * pcs->units[Q_DEPTH] - pcs->z[Q_DEPTH];
1130      dz *= pcs->sc[Q_DEPTH];
1131   } else {
1132      dz = VAL(ToDepth) - VAL(FrDepth);
1133      dz *= pcs->units[Q_DEPTH] * pcs->sc[Q_DEPTH];
1134   }
1135
1136   /* adjusted tape is negative -- probably the calibration is wrong */
1137   if (tape < (real)0.0) {
1138      compile_warning(/*Negative adjusted tape reading*/79);
1139   }
1140
1141   /* check if tape is less than depth change */
1142   if (tape < fabs(dz)) {
1143      /* FIXME: allow margin of error based on variances? */
1144      compile_warning(/*Tape reading is less than change in depth*/62);
1145   }
1146
1147   if (tape == (real)0.0 && dz == 0.0) {
1148      dx = dy = dz = (real)0.0;
1149      vx = vy = vz = (real)(var(Q_POS) / 3.0); /* Position error only */
1150   } else if (VAL(Comp) == HUGE_REAL &&
1151              VAL(BackComp) == HUGE_REAL) {
1152      /* plumb */
1153      dx = dy = (real)0.0;
1154      if (dz < 0) tape = -tape;
1155      /* FIXME: Should use FrDepth sometimes... */
1156      dz = (dz * VAR(Tape) + tape * 2 * VAR(ToDepth))
1157         / (VAR(Tape) * 2 * VAR(ToDepth));
1158      vx = vy = var(Q_POS) / 3.0 + dz * dz * var(Q_PLUMB);
1159      /* FIXME: Should use FrDepth sometimes... */
1160      vz = var(Q_POS) / 3.0 + VAR(Tape) * 2 * VAR(ToDepth)
1161                              / (VAR(Tape) + VAR(ToDepth));
1162   } else {
1163      real L2, sinB, cosB, dz2, D2;
1164      real var_comp;
1165      real comp = handle_compass(&var_comp);
1166      sinB = sin(comp);
1167      cosB = cos(comp);
1168      L2 = tape * tape;
1169      dz2 = dz * dz;
1170      D2 = L2 - dz2;
1171      if (D2 <= (real)0.0) {
1172         /* FIXME: Should use FrDepth sometimes... */
1173         real vsum = VAR(Tape) + 2 * VAR(ToDepth);
1174         dx = dy = (real)0.0;
1175         vx = vy = var(Q_POS) / 3.0;
1176         /* FIXME: Should use FrDepth sometimes... */
1177         vz = var(Q_POS) / 3.0 + VAR(Tape) * 2 * VAR(ToDepth) / vsum;
1178         if (dz > 0) {
1179            /* FIXME: Should use FrDepth sometimes... */
1180            dz = (dz * VAR(Tape) + tape * 2 * VAR(ToDepth)) / vsum;
1181         } else {
1182            dz = (dz * VAR(Tape) - tape * 2 * VAR(ToDepth)) / vsum;
1183         }
1184      } else {
1185         real D = sqrt(D2);
1186         /* FIXME: Should use FrDepth sometimes... */
1187         real F = VAR(Tape) * L2 + 2 * VAR(ToDepth) * D2;
1188         dx = D * sinB;
1189         dy = D * cosB;
1190
1191         vx = var(Q_POS) / 3.0 +
1192            sinB * sinB * F / D2 + var_comp * dy * dy;
1193         vy = var(Q_POS) / 3.0 +
1194            cosB * cosB * F / D2 + var_comp * dx * dx;
1195         /* FIXME: Should use FrDepth sometimes... */
1196         vz = var(Q_POS) / 3.0 + 2 * VAR(ToDepth);
1197
1198#ifndef NO_COVARIANCES
1199         cxy = sinB * cosB * (F / D2 + var_comp * D2);
1200         /* FIXME: Should use FrDepth sometimes... */
1201         cyz = -2 * VAR(ToDepth) * dy / D;
1202         czx = -2 * VAR(ToDepth) * dx / D;
1203#endif
1204      }
1205   }
1206   addlegbyname(fr, to, fToFirst, dx, dy, dz, vx, vy, vz
1207#ifndef NO_COVARIANCES
1208                , cxy, cyz, czx
1209#endif
1210                );
1211   return 1;
1212}
1213
1214static int
1215process_cartesian(prefix *fr, prefix *to, bool fToFirst)
1216{
1217   real dx = (VAL(Dx) * pcs->units[Q_DX] - pcs->z[Q_DX]) * pcs->sc[Q_DX];
1218   real dy = (VAL(Dy) * pcs->units[Q_DY] - pcs->z[Q_DY]) * pcs->sc[Q_DY];
1219   real dz = (VAL(Dz) * pcs->units[Q_DZ] - pcs->z[Q_DZ]) * pcs->sc[Q_DZ];
1220
1221   addlegbyname(fr, to, fToFirst, dx, dy, dz, VAR(Dx), VAR(Dy), VAR(Dz)
1222#ifndef NO_COVARIANCES
1223                , 0, 0, 0
1224#endif
1225                );
1226   return 1;
1227}
1228
1229static void
1230data_cartesian(void)
1231{
1232   prefix *fr = NULL, *to = NULL;
1233
1234   bool fMulti = fFalse;
1235
1236   reading first_stn = End;
1237
1238   reading *ordering;
1239
1240   again:
1241
1242   for (ordering = pcs->ordering ; ; ordering++) {
1243      skipblanks();
1244      switch (*ordering) {
1245       case Fr:
1246         fr = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1247         if (first_stn == End) first_stn = Fr;
1248         break;
1249       case To:
1250         to = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1251         if (first_stn == End) first_stn = To;
1252         break;
1253       case Station:
1254         fr = to;
1255         to = read_prefix(PFX_STATION);
1256         first_stn = To;
1257         break;
1258       case Dx: case Dy: case Dz:
1259         read_reading(*ordering, fFalse);
1260         break;
1261       case Ignore:
1262         skipword(); break;
1263       case IgnoreAllAndNewLine:
1264         skipline();
1265         /* fall through */
1266       case Newline:
1267         if (fr != NULL) {
1268            if (!process_cartesian(fr, to, first_stn == To))
1269               skipline();
1270         }
1271         fMulti = fTrue;
1272         while (1) {
1273            process_eol();
1274            process_bol();
1275            if (isData(ch)) break;
1276            if (!isComm(ch)) {
1277               push_back(ch);
1278               return;
1279            }
1280         }
1281         break;
1282       case IgnoreAll:
1283         skipline();
1284         /* fall through */
1285       case End:
1286         if (!fMulti) {
1287            process_cartesian(fr, to, first_stn == To);
1288            process_eol();
1289            return;
1290         }
1291         do {
1292            process_eol();
1293            process_bol();
1294         } while (isComm(ch));
1295         goto again;
1296       default: BUG("Unknown reading in ordering");
1297      }
1298   }
1299}
1300
1301static int
1302process_cylpolar(prefix *fr, prefix *to, bool fToFirst, bool fDepthChange)
1303{
1304   real tape = VAL(Tape);
1305
1306   real dx, dy, dz;
1307   real vx, vy, vz;
1308#ifndef NO_COVARIANCES
1309   real cxy = 0;
1310#endif
1311
1312   handle_comp_units();
1313
1314   /* depth gauge readings increase upwards with default calibration */
1315   if (fDepthChange) {
1316      SVX_ASSERT(VAL(FrDepth) == 0.0);
1317      dz = VAL(ToDepth) * pcs->units[Q_DEPTH] - pcs->z[Q_DEPTH];
1318      dz *= pcs->sc[Q_DEPTH];
1319   } else {
1320      dz = VAL(ToDepth) - VAL(FrDepth);
1321      dz *= pcs->units[Q_DEPTH] * pcs->sc[Q_DEPTH];
1322   }
1323
1324   /* adjusted tape is negative -- probably the calibration is wrong */
1325   if (tape < (real)0.0) {
1326      compile_warning(/*Negative adjusted tape reading*/79);
1327   }
1328
1329   if (VAL(Comp) == HUGE_REAL && VAL(BackComp) == HUGE_REAL) {
1330      /* plumb */
1331      dx = dy = (real)0.0;
1332      vx = vy = var(Q_POS) / 3.0 + dz * dz * var(Q_PLUMB);
1333      /* FIXME: Should use FrDepth sometimes... */
1334      vz = var(Q_POS) / 3.0 + 2 * VAR(ToDepth);
1335   } else {
1336      real sinB, cosB;
1337      real var_comp;
1338      real comp = handle_compass(&var_comp);
1339      sinB = sin(comp);
1340      cosB = cos(comp);
1341
1342      dx = tape * sinB;
1343      dy = tape * cosB;
1344
1345      vx = var(Q_POS) / 3.0 +
1346         VAR(Tape) * sinB * sinB + var_comp * dy * dy;
1347      vy = var(Q_POS) / 3.0 +
1348         VAR(Tape) * cosB * cosB + var_comp * dx * dx;
1349      /* FIXME: Should use FrDepth sometimes... */
1350      vz = var(Q_POS) / 3.0 + 2 * VAR(ToDepth);
1351
1352#ifndef NO_COVARIANCES
1353      cxy = (VAR(Tape) - var_comp * tape * tape) * sinB * cosB;
1354#endif
1355   }
1356   addlegbyname(fr, to, fToFirst, dx, dy, dz, vx, vy, vz
1357#ifndef NO_COVARIANCES
1358                , cxy, 0, 0
1359#endif
1360                );
1361   return 1;
1362}
1363
1364/* Process tape/compass/clino, diving, and cylpolar styles of survey data
1365 * Also handles topofil (fromcount/tocount or count) in place of tape */
1366static void
1367data_normal(void)
1368{
1369   prefix *fr = NULL, *to = NULL;
1370   reading first_stn = End;
1371
1372   bool fTopofil = fFalse, fMulti = fFalse;
1373   bool fRev;
1374   clino_type ctype, backctype;
1375   bool fDepthChange;
1376   unsigned long compass_dat_flags = 0;
1377
1378   reading *ordering;
1379
1380   VAL(Tape) = 0;
1381   VAL(Comp) = VAL(BackComp) = HUGE_REAL;
1382   VAL(FrCount) = VAL(ToCount) = 0;
1383   VAL(FrDepth) = VAL(ToDepth) = 0;
1384   VAL(Left) = VAL(Right) = VAL(Up) = VAL(Down) = HUGE_REAL;
1385
1386   fRev = fFalse;
1387   ctype = backctype = CTYPE_OMIT;
1388   fDepthChange = fFalse;
1389
1390   /* ordering may omit clino reading, so set up default here */
1391   /* this is also used if clino reading is the omit character */
1392   VAL(Clino) = VAL(BackClino) = 0;
1393
1394   again:
1395
1396   /* We clear these flags in the normal course of events, but if there's an
1397    * error in a reading, we might not, so make sure it has been cleared here.
1398    */
1399   pcs->flags &= ~(BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY));
1400   for (ordering = pcs->ordering; ; ordering++) {
1401      skipblanks();
1402      switch (*ordering) {
1403       case Fr:
1404          fr = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_ANON);
1405          if (first_stn == End) first_stn = Fr;
1406          break;
1407       case To:
1408          to = read_prefix(PFX_STATION|PFX_ALLOW_ROOT|PFX_ANON);
1409          if (first_stn == End) first_stn = To;
1410          break;
1411       case Station:
1412          fr = to;
1413          to = read_prefix(PFX_STATION);
1414          first_stn = To;
1415          break;
1416       case Dir: {
1417          typedef enum {
1418             DIR_NULL=-1, DIR_FORE, DIR_BACK
1419          } dir_tok;
1420          static sztok dir_tab[] = {
1421             {"B",     DIR_BACK},
1422             {"F",     DIR_FORE},
1423          };
1424          dir_tok tok;
1425          get_token();
1426          tok = match_tok(dir_tab, TABSIZE(dir_tab));
1427          switch (tok) {
1428           case DIR_FORE:
1429             break;
1430           case DIR_BACK:
1431             fRev = fTrue;
1432             break;
1433           default:
1434             file.lpos += strlen(buffer);
1435             compile_error_skip(-/*Found “%s”, expecting “F” or “B”*/131,
1436                                buffer);
1437             process_eol();
1438             return;
1439          }
1440          break;
1441       }
1442       case Tape:
1443          read_reading(Tape, fFalse);
1444          if (VAL(Tape) < (real)0.0)
1445             compile_warning(-/*Negative tape reading*/60);
1446          break;
1447       case Count:
1448          VAL(FrCount) = VAL(ToCount);
1449          read_reading(ToCount, fFalse);
1450          fTopofil = fTrue;
1451          break;
1452       case FrCount:
1453          read_reading(FrCount, fFalse);
1454          break;
1455       case ToCount:
1456          read_reading(ToCount, fFalse);
1457          fTopofil = fTrue;
1458          break;
1459       case Comp: case BackComp:
1460          read_bearing_or_omit(*ordering);
1461          break;
1462       case Clino: case BackClino: {
1463          reading r = *ordering;
1464          clino_type * p_ctype = (r == Clino ? &ctype : &backctype);
1465          read_reading(r, fTrue);
1466          if (VAL(r) == HUGE_REAL) {
1467             VAL(r) = handle_plumb(p_ctype);
1468             if (VAL(r) != HUGE_REAL) break;
1469             compile_error_token(-/*Expecting numeric field, found “%s”*/9);
1470             skipline();
1471             process_eol();
1472             return;
1473          }
1474          *p_ctype = CTYPE_READING;
1475          break;
1476       }
1477       case FrDepth: case ToDepth:
1478          read_reading(*ordering, fFalse);
1479          break;
1480       case Depth:
1481          VAL(FrDepth) = VAL(ToDepth);
1482          read_reading(ToDepth, fFalse);
1483          break;
1484       case DepthChange:
1485          fDepthChange = fTrue;
1486          VAL(FrDepth) = 0;
1487          read_reading(ToDepth, fFalse);
1488          break;
1489       case CompassDATComp:
1490          read_bearing_or_omit(Comp);
1491          if (is_compass_NaN(VAL(Comp))) VAL(Comp) = HUGE_REAL;
1492          break;
1493       case CompassDATBackComp:
1494          read_bearing_or_omit(BackComp);
1495          if (is_compass_NaN(VAL(BackComp))) VAL(BackComp) = HUGE_REAL;
1496          break;
1497       case CompassDATClino: case CompassDATBackClino: {
1498          reading r;
1499          clino_type * p_ctype;
1500          if (*ordering == CompassDATClino) {
1501             r = Clino;
1502             p_ctype = &ctype;
1503          } else {
1504             r = BackClino;
1505             p_ctype = &backctype;
1506          }
1507          read_reading(r, fFalse);
1508          if (is_compass_NaN(VAL(r))) {
1509             VAL(r) = HUGE_REAL;
1510             *p_ctype = CTYPE_OMIT;
1511          } else {
1512             *p_ctype = CTYPE_READING;
1513          }
1514          break;
1515       }
1516       case CompassDATLeft: case CompassDATRight:
1517       case CompassDATUp: case CompassDATDown: {
1518          /* FIXME: need to actually make use of these entries! */
1519          reading actual = Left + (*ordering - CompassDATLeft);
1520          read_reading(actual, fFalse);
1521          if (VAL(actual) < 0) VAL(actual) = HUGE_REAL;
1522          break;
1523       }
1524       case CompassDATFlags:
1525          if (ch == '#') {
1526             nextch();
1527             if (ch == '|') {
1528                filepos fp;
1529                get_pos(&fp);
1530                nextch();
1531                while (ch >= 'A' && ch <= 'Z') {
1532                   compass_dat_flags |= BIT(ch - 'A');
1533                   /* FIXME: we currently understand X (exclude data)
1534                    * but should also handle at least some of:
1535                    * L exclude from length
1536                    * P no plot
1537                    * C no adjustment
1538                    */
1539                   nextch();
1540                }
1541                if (ch == '#') {
1542                   nextch();
1543                } else {
1544                   compass_dat_flags = 0;
1545                   set_pos(&fp);
1546                   push_back('|');
1547                   ch = '#';
1548                }
1549             } else {
1550                push_back(ch);
1551                ch = '#';
1552             }
1553          }
1554          break;
1555       case Ignore:
1556          skipword(); break;
1557       case IgnoreAllAndNewLine:
1558          skipline();
1559          /* fall through */
1560       case Newline:
1561          if (fr != NULL) {
1562             int r;
1563             int save_flags;
1564             int implicit_splay;
1565             if (fTopofil)
1566                VAL(Tape) = VAL(ToCount) - VAL(FrCount);
1567             /* Note: frdepth == todepth test works regardless of fDepthChange
1568              * (frdepth always zero, todepth is change of depth) and also
1569              * works for STYLE_NORMAL (both remain 0) */
1570             if (TSTBIT(pcs->infer, INFER_EQUATES) &&
1571                 VAL(Tape) == (real)0.0 && VAL(FrDepth) == VAL(ToDepth)) {
1572                process_equate(fr, to);
1573                goto inferred_equate;
1574             }
1575             if (fRev) {
1576                prefix *t = fr;
1577                fr = to;
1578                to = t;
1579             }
1580             if (fTopofil) {
1581                VAL(Tape) *= pcs->units[Q_COUNT] * pcs->sc[Q_COUNT];
1582             } else {
1583                VAL(Tape) *= pcs->units[Q_LENGTH];
1584                VAL(Tape) -= pcs->z[Q_LENGTH];
1585                VAL(Tape) *= pcs->sc[Q_LENGTH];
1586             }
1587             implicit_splay = TSTBIT(pcs->flags, FLAGS_IMPLICIT_SPLAY);
1588             pcs->flags &= ~(BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY));
1589             save_flags = pcs->flags;
1590             if (implicit_splay) {
1591                pcs->flags |= BIT(FLAGS_SPLAY);
1592             }
1593             switch (pcs->style) {
1594              case STYLE_NORMAL:
1595                r = process_normal(fr, to, (first_stn == To) ^ fRev,
1596                                   ctype, backctype);
1597                break;
1598              case STYLE_DIVING:
1599                r = process_diving(fr, to, (first_stn == To) ^ fRev,
1600                                   fDepthChange);
1601                break;
1602              case STYLE_CYLPOLAR:
1603                r = process_cylpolar(fr, to, (first_stn == To) ^ fRev,
1604                                     fDepthChange);
1605                break;
1606              default:
1607                r = 0; /* avoid warning */
1608                BUG("bad style");
1609             }
1610             pcs->flags = save_flags;
1611             if (!r) skipline();
1612
1613             /* Swap fr and to back to how they were for next line */
1614             if (fRev) {
1615                prefix *t = fr;
1616                fr = to;
1617                to = t;
1618             }
1619          }
1620
1621          fRev = fFalse;
1622          ctype = backctype = CTYPE_OMIT;
1623          fDepthChange = fFalse;
1624
1625          /* ordering may omit clino reading, so set up default here */
1626          /* this is also used if clino reading is the omit character */
1627          VAL(Clino) = VAL(BackClino) = 0;
1628
1629          inferred_equate:
1630
1631          fMulti = fTrue;
1632          while (1) {
1633              process_eol();
1634              process_bol();
1635              if (isData(ch)) break;
1636              if (!isComm(ch)) {
1637                 push_back(ch);
1638                 return;
1639              }
1640          }
1641          break;
1642       case IgnoreAll:
1643          skipline();
1644          /* fall through */
1645       case End:
1646          if (!fMulti) {
1647             int save_flags;
1648             int implicit_splay;
1649             /* Compass ignore flag is 'X' */
1650             if ((compass_dat_flags & BIT('X' - 'A'))) {
1651                process_eol();
1652                return;
1653             }
1654             if (fRev) {
1655                prefix *t = fr;
1656                fr = to;
1657                to = t;
1658             }
1659             if (fTopofil) VAL(Tape) = VAL(ToCount) - VAL(FrCount);
1660             /* Note: frdepth == todepth test works regardless of fDepthChange
1661              * (frdepth always zero, todepth is change of depth) and also
1662              * works for STYLE_NORMAL (both remain 0) */
1663             if (TSTBIT(pcs->infer, INFER_EQUATES) &&
1664                 VAL(Tape) == (real)0.0 && VAL(FrDepth) == VAL(ToDepth)) {
1665                process_equate(fr, to);
1666                process_eol();
1667                return;
1668             }
1669             if (fTopofil) {
1670                VAL(Tape) *= pcs->units[Q_COUNT] * pcs->sc[Q_COUNT];
1671             } else {
1672                VAL(Tape) *= pcs->units[Q_LENGTH];
1673                VAL(Tape) -= pcs->z[Q_LENGTH];
1674                VAL(Tape) *= pcs->sc[Q_LENGTH];
1675             }
1676             implicit_splay = TSTBIT(pcs->flags, FLAGS_IMPLICIT_SPLAY);
1677             pcs->flags &= ~(BIT(FLAGS_ANON_ONE_END) | BIT(FLAGS_IMPLICIT_SPLAY));
1678             save_flags = pcs->flags;
1679             if (implicit_splay) {
1680                pcs->flags |= BIT(FLAGS_SPLAY);
1681             }
1682             switch (pcs->style) {
1683              case STYLE_NORMAL:
1684                process_normal(fr, to, (first_stn == To) ^ fRev,
1685                               ctype, backctype);
1686                break;
1687              case STYLE_DIVING:
1688                process_diving(fr, to, (first_stn == To) ^ fRev,
1689                               fDepthChange);
1690                break;
1691              case STYLE_CYLPOLAR:
1692                process_cylpolar(fr, to, (first_stn == To) ^ fRev,
1693                                 fDepthChange);
1694                break;
1695              default:
1696                BUG("bad style");
1697             }
1698             pcs->flags = save_flags;
1699
1700             process_eol();
1701             return;
1702          }
1703          do {
1704             process_eol();
1705             process_bol();
1706          } while (isComm(ch));
1707          goto again;
1708       default:
1709          BUG("Unknown reading in ordering");
1710      }
1711   }
1712}
1713
1714static int
1715process_lrud(prefix *stn)
1716{
1717   SVX_ASSERT(next_lrud);
1718   lrud * xsect = osnew(lrud);
1719   xsect->stn = stn;
1720   xsect->l = (VAL(Left) * pcs->units[Q_LEFT] - pcs->z[Q_LEFT]) * pcs->sc[Q_LEFT];
1721   xsect->r = (VAL(Right) * pcs->units[Q_RIGHT] - pcs->z[Q_RIGHT]) * pcs->sc[Q_RIGHT];
1722   xsect->u = (VAL(Up) * pcs->units[Q_UP] - pcs->z[Q_UP]) * pcs->sc[Q_UP];
1723   xsect->d = (VAL(Down) * pcs->units[Q_DOWN] - pcs->z[Q_DOWN]) * pcs->sc[Q_DOWN];
1724   xsect->meta = pcs->meta;
1725   if (pcs->meta) ++pcs->meta->ref_count;
1726   xsect->next = NULL;
1727   *next_lrud = xsect;
1728   next_lrud = &(xsect->next);
1729
1730   return 1;
1731}
1732
1733static void
1734data_passage(void)
1735{
1736   prefix *stn = NULL;
1737   reading *ordering;
1738
1739   for (ordering = pcs->ordering ; ; ordering++) {
1740      skipblanks();
1741      switch (*ordering) {
1742       case Station:
1743         stn = read_prefix(PFX_STATION);
1744         break;
1745       case Left: case Right: case Up: case Down:
1746         read_reading(*ordering, fTrue);
1747         if (VAL(*ordering) == HUGE_REAL) {
1748            if (!isOmit(ch)) {
1749               compile_error_token(-/*Expecting numeric field, found “%s”*/9);
1750            } else {
1751               nextch();
1752            }
1753            VAL(*ordering) = -1;
1754         }
1755         break;
1756       case Ignore:
1757         skipword(); break;
1758       case IgnoreAll:
1759         skipline();
1760         /* fall through */
1761       case End: {
1762         process_lrud(stn);
1763         process_eol();
1764         return;
1765       }
1766       default: BUG("Unknown reading in ordering");
1767      }
1768   }
1769}
1770
1771static int
1772process_nosurvey(prefix *fr, prefix *to, bool fToFirst)
1773{
1774   nosurveylink *link;
1775
1776   /* Suppress "unused fixed point" warnings for these stations */
1777   fr->sflags |= BIT(SFLAGS_USED);
1778   to->sflags |= BIT(SFLAGS_USED);
1779
1780   /* add to linked list which is dealt with after network is solved */
1781   link = osnew(nosurveylink);
1782   if (fToFirst) {
1783      link->to = StnFromPfx(to);
1784      link->fr = StnFromPfx(fr);
1785   } else {
1786      link->fr = StnFromPfx(fr);
1787      link->to = StnFromPfx(to);
1788   }
1789   link->flags = pcs->flags | (STYLE_NOSURVEY << FLAGS_STYLE_BIT0);
1790   link->meta = pcs->meta;
1791   if (pcs->meta) ++pcs->meta->ref_count;
1792   link->next = nosurveyhead;
1793   nosurveyhead = link;
1794   return 1;
1795}
1796
1797static void
1798data_nosurvey(void)
1799{
1800   prefix *fr = NULL, *to = NULL;
1801
1802   bool fMulti = fFalse;
1803
1804   reading first_stn = End;
1805
1806   reading *ordering;
1807
1808   again:
1809
1810   for (ordering = pcs->ordering ; ; ordering++) {
1811      skipblanks();
1812      switch (*ordering) {
1813       case Fr:
1814          fr = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1815          if (first_stn == End) first_stn = Fr;
1816          break;
1817       case To:
1818          to = read_prefix(PFX_STATION|PFX_ALLOW_ROOT);
1819          if (first_stn == End) first_stn = To;
1820          break;
1821       case Station:
1822          fr = to;
1823          to = read_prefix(PFX_STATION);
1824          first_stn = To;
1825          break;
1826       case Ignore:
1827         skipword(); break;
1828       case IgnoreAllAndNewLine:
1829         skipline();
1830         /* fall through */
1831       case Newline:
1832         if (fr != NULL) {
1833            if (!process_nosurvey(fr, to, first_stn == To))
1834               skipline();
1835         }
1836         if (ordering[1] == End) {
1837            do {
1838               process_eol();
1839               process_bol();
1840            } while (isComm(ch));
1841            if (!isData(ch)) {
1842               push_back(ch);
1843               return;
1844            }
1845            goto again;
1846         }
1847         fMulti = fTrue;
1848         while (1) {
1849            process_eol();
1850            process_bol();
1851            if (isData(ch)) break;
1852            if (!isComm(ch)) {
1853               push_back(ch);
1854               return;
1855            }
1856         }
1857         break;
1858       case IgnoreAll:
1859         skipline();
1860         /* fall through */
1861       case End:
1862         if (!fMulti) {
1863            (void)process_nosurvey(fr, to, first_stn == To);
1864            process_eol();
1865            return;
1866         }
1867         do {
1868            process_eol();
1869            process_bol();
1870         } while (isComm(ch));
1871         goto again;
1872       default: BUG("Unknown reading in ordering");
1873      }
1874   }
1875}
1876
1877/* totally ignore a line of survey data */
1878static void
1879data_ignore(void)
1880{
1881   skipline();
1882   process_eol();
1883}
Note: See TracBrowser for help on using the repository browser.