Tweak code formatting
[survex.git] / src / cavern.c
blob266426ba7b494d577724d4a8f6ebaa399866c1cf
1 /* cavern.c
2 * SURVEX Cave surveying software: data reduction main and related functions
3 * Copyright (C) 1991-2003,2004,2005,2010,2011,2013,2014,2015,2016 Olly Betts
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <limits.h>
25 #include <stdlib.h>
26 #include <time.h>
28 #include "cavern.h"
29 #include "cmdline.h"
30 #include "commands.h"
31 #include "date.h"
32 #include "datain.h"
33 #include "debug.h"
34 #include "message.h"
35 #include "filename.h"
36 #include "filelist.h"
37 #include "img_hosted.h"
38 #include "listpos.h"
39 #include "netbits.h"
40 #include "netskel.h"
41 #include "osdepend.h"
42 #include "out.h"
43 #include "str.h"
44 #include "validate.h"
45 #include "whichos.h"
47 #if OS_WIN32
48 # include <conio.h> /* for _kbhit() and _getch() */
49 #endif
51 /* For funcs which want to be immune from messing around with different
52 * calling conventions */
53 #ifndef CDECL
54 # define CDECL
55 #endif
57 /* Globals */
58 node *stnlist = NULL;
59 settings *pcs;
60 prefix *root;
61 prefix *anon_list = NULL;
62 long cLegs, cStns;
63 long cComponents;
64 bool fExportUsed = fFalse;
65 projPJ proj_out = NULL;
66 char * proj_str_out = NULL;
68 FILE *fhErrStat = NULL;
69 img *pimg = NULL;
70 bool fQuiet = fFalse; /* just show brief summary + errors */
71 bool fMute = fFalse; /* just show errors */
72 bool fSuppress = fFalse; /* only output 3d file */
73 static bool fLog = fFalse; /* stdout to .log file */
74 static bool f_warnings_are_errors = fFalse; /* turn warnings into errors */
76 nosurveylink *nosurveyhead;
78 real totadj, total, totplan, totvert;
79 real min[3], max[3];
80 prefix *pfxHi[3], *pfxLo[3];
82 char *survey_title = NULL;
83 int survey_title_len;
85 bool fExplicitTitle = fFalse;
87 char *fnm_output_base = NULL;
88 int fnm_output_base_is_dir = 0;
90 lrudlist * model = NULL;
91 lrud ** next_lrud = NULL;
93 static void do_stats(void);
95 static const struct option long_opts[] = {
96 /* const char *name; int has_arg (0 no_argument, 1 required_*, 2 optional_*); int *flag; int val; */
97 {"percentage", no_argument, 0, 'p'},
98 /* Ignore for compatibility with older versions. */
99 {"no-percentage", no_argument, 0, 0},
100 {"output", required_argument, 0, 'o'},
101 {"quiet", no_argument, 0, 'q'},
102 {"no-auxiliary-files", no_argument, 0, 's'},
103 {"warnings-are-errors", no_argument, 0, 'w'},
104 {"log", no_argument, 0, 1},
105 {"3d-version", required_argument, 0, 'v'},
106 #if OS_WIN32
107 {"pause", no_argument, 0, 2},
108 #endif
109 {"help", no_argument, 0, HLP_HELP},
110 {"version", no_argument, 0, HLP_VERSION},
111 {0, 0, 0, 0}
114 #define short_opts "pao:qsv:wz:"
116 static struct help_msg help[] = {
117 /* <-- */
118 /* TRANSLATORS: --help output for cavern --output option */
119 {HLP_ENCODELONG(2), /*set location for output files*/162, 0},
120 /* TRANSLATORS: --help output for cavern --quiet option */
121 {HLP_ENCODELONG(3), /*only show brief summary (-qq for errors only)*/163, 0},
122 /* TRANSLATORS: --help output for cavern --no-auxiliary-files option */
123 {HLP_ENCODELONG(4), /*do not create .err file*/164, 0},
124 /* TRANSLATORS: --help output for cavern --warnings-are-errors option */
125 {HLP_ENCODELONG(5), /*turn warnings into errors*/165, 0},
126 /* TRANSLATORS: --help output for cavern --log option */
127 {HLP_ENCODELONG(6), /*log output to .log file*/170, 0},
128 /* TRANSLATORS: --help output for cavern --3d-version option */
129 {HLP_ENCODELONG(7), /*specify the 3d file format version to output*/171, 0},
130 /*{'z', "set optimizations for network reduction"},*/
131 {0, 0, 0}
134 /* atexit functions */
135 static void
136 delete_output_on_error(void)
138 if (msg_errors || (f_warnings_are_errors && msg_warnings))
139 filename_delete_output();
142 #if OS_WIN32
143 static void
144 pause_on_exit(void)
146 while (_kbhit()) _getch();
147 _getch();
149 #endif
151 int current_days_since_1900;
153 extern CDECL int
154 main(int argc, char **argv)
156 int d;
157 time_t tmUserStart = time(NULL);
158 clock_t tmCPUStart = clock();
160 /* FIXME: localtime? */
161 struct tm * t = localtime(&tmUserStart);
162 int y = t->tm_year + 1900;
163 current_days_since_1900 = days_since_1900(y, t->tm_mon + 1, t->tm_mday);
166 /* Always buffer by line for aven's benefit. */
167 setvbuf(stdout, NULL, _IOLBF, 0);
169 msg_init(argv);
171 #if OS_WIN32 || OS_UNIX_MACOSX
172 pj_set_finder(msg_proj_finder);
173 #endif
175 pcs = osnew(settings);
176 pcs->next = NULL;
177 pcs->Translate = ((short*) osmalloc(ossizeof(short) * 257)) + 1;
178 pcs->meta = NULL;
179 pcs->proj = NULL;
180 pcs->declination = HUGE_REAL;
181 pcs->convergence = 0.0;
183 /* Set up root of prefix hierarchy */
184 root = osnew(prefix);
185 root->up = root->right = root->down = NULL;
186 root->stn = NULL;
187 root->pos = NULL;
188 root->ident = NULL;
189 root->min_export = root->max_export = 0;
190 root->sflags = BIT(SFLAGS_SURVEY);
191 root->filename = NULL;
193 nosurveyhead = NULL;
195 stnlist = NULL;
196 cLegs = cStns = cComponents = 0;
197 totadj = total = totplan = totvert = 0.0;
199 for (d = 0; d <= 2; d++) {
200 min[d] = HUGE_REAL;
201 max[d] = -HUGE_REAL;
202 pfxHi[d] = pfxLo[d] = NULL;
205 /* at least one argument must be given */
206 cmdline_init(argc, argv, short_opts, long_opts, NULL, help, 1, -1);
207 while (1) {
208 int opt = cmdline_getopt();
209 if (opt == EOF) break;
210 switch (opt) {
211 case 'p':
212 /* Ignore for compatibility with older versions. */
213 break;
214 case 'o': {
215 osfree(fnm_output_base); /* in case of multiple -o options */
216 /* can be a directory (in which case use basename of leaf input)
217 * or a file (in which case just trim the extension off) */
218 if (fDirectory(optarg)) {
219 /* this is a little tricky - we need to note the path here,
220 * and then add the leaf later on (in datain.c) */
221 fnm_output_base = base_from_fnm(optarg);
222 fnm_output_base_is_dir = 1;
223 } else {
224 fnm_output_base = base_from_fnm(optarg);
226 break;
228 case 'q':
229 if (fQuiet) fMute = 1;
230 fQuiet = 1;
231 break;
232 case 's':
233 fSuppress = 1;
234 break;
235 case 'v': {
236 int v = atoi(optarg);
237 if (v < IMG_VERSION_MIN || v > IMG_VERSION_MAX)
238 fatalerror(/*3d file format versions %d to %d supported*/88,
239 IMG_VERSION_MIN, IMG_VERSION_MAX);
240 img_output_version = v;
241 break;
243 case 'w':
244 f_warnings_are_errors = 1;
245 break;
246 case 'z': {
247 /* Control which network optimisations are used (development tool) */
248 static int first_opt_z = 1;
249 char c;
250 if (first_opt_z) {
251 optimize = 0;
252 first_opt_z = 0;
254 /* Lollipops, Parallel legs, Iterate mx, Delta* */
255 while ((c = *optarg++) != '\0')
256 if (islower((unsigned char)c)) optimize |= BITA(c);
257 break;
258 case 1:
259 fLog = fTrue;
260 break;
261 #if OS_WIN32
262 case 2:
263 atexit(pause_on_exit);
264 break;
265 #endif
270 if (fLog) {
271 char *fnm;
272 if (!fnm_output_base) {
273 char *p;
274 p = baseleaf_from_fnm(argv[optind]);
275 fnm = add_ext(p, EXT_LOG);
276 osfree(p);
277 } else if (fnm_output_base_is_dir) {
278 char *p;
279 fnm = baseleaf_from_fnm(argv[optind]);
280 p = use_path(fnm_output_base, fnm);
281 osfree(fnm);
282 fnm = add_ext(p, EXT_LOG);
283 osfree(p);
284 } else {
285 fnm = add_ext(fnm_output_base, EXT_LOG);
288 if (!freopen(fnm, "w", stdout))
289 fatalerror(/*Failed to open output file “%s”*/47, fnm);
291 osfree(fnm);
294 if (!fMute) {
295 const char *p = COPYRIGHT_MSG;
296 puts(PRETTYPACKAGE" "VERSION);
297 while (1) {
298 const char *q = p;
299 p = strstr(p, "(C)");
300 if (p == NULL) {
301 puts(q);
302 break;
304 fwrite(q, 1, p - q, stdout);
305 fputs(msg(/*©*/0), stdout);
306 p += 3;
310 atexit(delete_output_on_error);
312 /* end of options, now process data files */
313 while (argv[optind]) {
314 const char *fnm = argv[optind];
316 if (!fExplicitTitle) {
317 char *lf;
318 lf = baseleaf_from_fnm(fnm);
319 if (survey_title) s_catchar(&survey_title, &survey_title_len, ' ');
320 s_cat(&survey_title, &survey_title_len, lf);
321 osfree(lf);
324 /* Select defaults settings */
325 default_all(pcs);
326 data_file(NULL, fnm); /* first argument is current path */
328 optind++;
331 validate();
333 solve_network(/*stnlist*/); /* Find coordinates of all points */
334 validate();
336 /* close .3d file */
337 if (!img_close(pimg)) {
338 char *fnm = add_ext(fnm_output_base, EXT_SVX_3D);
339 fatalerror(img_error2msg(img_error()), fnm);
341 if (fhErrStat) safe_fclose(fhErrStat);
343 out_current_action(msg(/*Calculating statistics*/120));
344 if (!fMute) do_stats();
345 if (!fQuiet) {
346 /* clock() typically wraps after 72 minutes, but there doesn't seem
347 * to be a better way. Still 72 minutes means some cave!
348 * We detect if clock() could have wrapped and suppress CPU time
349 * printing in this case.
351 double tmUser = difftime(time(NULL), tmUserStart);
352 double tmCPU;
353 clock_t now = clock();
354 #define CLOCK_T_WRAP \
355 (sizeof(clock_t)<sizeof(long)?(1ul << (CHAR_BIT * sizeof(clock_t))):0)
356 tmCPU = (now - (unsigned long)tmCPUStart)
357 / (double)CLOCKS_PER_SEC;
358 if (now < tmCPUStart)
359 tmCPU += CLOCK_T_WRAP / (double)CLOCKS_PER_SEC;
360 if (tmUser >= tmCPU + CLOCK_T_WRAP / (double)CLOCKS_PER_SEC)
361 tmCPU = 0;
363 /* tmUser is integer, tmCPU not - equivalent to (ceil(tmCPU) >= tmUser) */
364 if (tmCPU + 1 > tmUser) {
365 printf(msg(/*CPU time used %5.2fs*/140), tmCPU);
366 } else if (tmCPU == 0) {
367 if (tmUser != 0.0) {
368 printf(msg(/*Time used %5.2fs*/141), tmUser);
369 } else {
370 fputs(msg(/*Time used unavailable*/142), stdout);
372 } else {
373 printf(msg(/*Time used %5.2fs (%5.2fs CPU time)*/143), tmUser, tmCPU);
375 putnl();
377 if (msg_warnings || msg_errors) {
378 if (msg_errors || (f_warnings_are_errors && msg_warnings)) {
379 printf(msg(/*There were %d warning(s) and %d error(s) - no output files produced.*/113),
380 msg_warnings, msg_errors);
381 putnl();
382 return EXIT_FAILURE;
384 printf(msg(/*There were %d warning(s).*/16), msg_warnings);
385 putnl();
387 return EXIT_SUCCESS;
390 static void
391 do_range(int d, int msgno, real length_factor, const char * units)
393 /* sprint_prefix uses a single buffer, so to report two stations in one
394 * message we need to make a temporary copy of the string for one of them.
396 char * pfx_hi = osstrdup(sprint_prefix(pfxHi[d]));
397 char * pfx_lo = sprint_prefix(pfxLo[d]);
398 real hi = max[d] * length_factor;
399 real lo = min[d] * length_factor;
400 printf(msg(msgno), hi - lo, units, pfx_hi, hi, units, pfx_lo, lo, units);
401 osfree(pfx_hi);
402 putnl();
405 static void
406 do_stats(void)
408 long cLoops = cComponents + cLegs - cStns;
409 int length_units = get_length_units(Q_LENGTH);
410 const char * units = get_units_string(length_units);
411 real length_factor = 1.0 / get_units_factor(length_units);
413 putnl();
415 if (cStns == 1) {
416 fputs(msg(/*Survey contains 1 survey station,*/172), stdout);
417 } else {
418 printf(msg(/*Survey contains %ld survey stations,*/173), cStns);
421 if (cLegs == 1) {
422 fputs(msg(/* joined by 1 leg.*/174), stdout);
423 } else {
424 printf(msg(/* joined by %ld legs.*/175), cLegs);
427 putnl();
429 if (cLoops == 1) {
430 fputs(msg(/*There is 1 loop.*/138), stdout);
431 } else {
432 printf(msg(/*There are %ld loops.*/139), cLoops);
435 putnl();
437 if (cComponents != 1) {
438 /* TRANSLATORS: "Connected component" in the graph theory sense - it
439 * means there are %ld bits of survey with no connections between them.
440 * This message is only used if there are more than 1. */
441 printf(msg(/*Survey has %ld connected components.*/178), cComponents);
442 putnl();
445 printf(msg(/*Total length of survey legs = %7.2f%s (%7.2f%s adjusted)*/132),
446 total * length_factor, units, totadj * length_factor, units);
447 putnl();
448 printf(msg(/*Total plan length of survey legs = %7.2f%s*/133),
449 totplan * length_factor, units);
450 putnl();
451 printf(msg(/*Total vertical length of survey legs = %7.2f%s*/134),
452 totvert * length_factor, units);
453 putnl();
455 /* If there's no underground survey, we've no ranges */
456 if (pfxHi[0]) {
457 /* TRANSLATORS: numbers are altitudes of highest and lowest stations */
458 do_range(2, /*Vertical range = %4.2f%s (from %s at %4.2f%s to %s at %4.2f%s)*/135,
459 length_factor, units);
460 /* TRANSLATORS: c.f. previous message */
461 do_range(1, /*North-South range = %4.2f%s (from %s at %4.2f%s to %s at %4.2f%s)*/136,
462 length_factor, units);
463 /* TRANSLATORS: c.f. previous two messages */
464 do_range(0, /*East-West range = %4.2f%s (from %s at %4.2f%s to %s at %4.2f%s)*/137,
465 length_factor, units);
468 print_node_stats();
469 /* Also, could give:
470 * # nodes stations (ie have other than two references or are fixed)
471 * # fixed stations (list of?)