source: git/src/datain.c @ 0c323ec

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernlogstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 0c323ec was 0040469d, checked in by Olly Betts <olly@…>, 10 years ago

src/datain.c: Tiny code simplification.

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