File: TideContext.cc

package info (click to toggle)
xtide 2.6.4-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,996 kB
  • ctags: 2,617
  • sloc: cpp: 26,266; ansic: 8,105; makefile: 152; yacc: 113; sh: 54; lex: 54
file content (492 lines) | stat: -rw-r--r-- 13,454 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// $Id: TideContext.cc,v 1.6 2003/02/04 15:53:46 flaterco Exp $
/*  TideContext  In lieu of global variables and functions.

    Copyright (C) 1998  David Flater.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "common.hh"

void version_string (Dstr &text_out) {
  text_out = "XTide ";
  text_out += VERSION;
  if (PATCHLEVEL) {
    text_out += ".";
    text_out += PATCHLEVEL;
  }
#ifdef VSTATUS
  text_out += " ";
  text_out += VSTATUS;
#endif
}

TideContext::TideContext (int in_argc, char **in_argv, Colors *in_colors,
Settings *in_settings) {

  // It's unfortunate that this gets done twice.
  cls = new CommandLineSettings(in_argc, in_argv);

  colors = in_colors;
  settings = in_settings;

  // Get HFILE_PATH from environment or /etc/xtide.conf and create
  // persistent HarmonicsPath
  Dstr hfile_path (getenv ("HFILE_PATH"));
  if (hfile_path.isNull()) {
    FILE *configfile;
    if ((configfile = fopen ("/etc/xtide.conf", "r"))) {
      hfile_path.getline (configfile);
      fclose (configfile);
    }
  }
  if (hfile_path.isNull())
    hfile_path = "harmonics.tcd";
  harmonicsPath = new HarmonicsPath (hfile_path);

  homedir = getenv ("HOME");
  if (homedir.isNull())
    barf (NOHOMEDIR);

  disabledisclaimerfile = homedir;
  disabledisclaimerfile += "/.disableXTidedisclaimer";

  // Get this only when needed.
  myStationIndex = NULL;
}

TideContext::~TideContext () {
  if (myStationIndex)
    delete myStationIndex;
  delete harmonicsPath;
  delete cls;
  delete colors;
  delete settings;
}

// THIS CODE IS DUPLICATED IN XXTIDECONTEXT!  The duplication is needed
// to embed XEvent polling in xxTideContext.
void TideContext::doHarmonicsFile (Dstr &fname) {
  Dstr msg ("Indexing ");
  msg += fname;
  msg += "...";
  log (msg, LOG_NOTICE);
  HarmonicsFile h (fname, settings);
  myStationIndex->addHfileId (h.version_string);
  StationRef *s;
  while ((s = h.getNextStationRef()))
    myStationIndex->add (s);
}

// THIS CODE IS DUPLICATED IN XXTIDECONTEXT!  The duplication is needed
// to embed XEvent polling in xxTideContext.
StationIndex *TideContext::stationIndex () {
  if (!myStationIndex) {
    myStationIndex = new StationIndex();
    for (unsigned i=0; i<harmonicsPath->length(); i++) {
      struct stat s;
      if (stat ((*harmonicsPath)[i].aschar(), &s) == 0) {
        if (S_ISDIR (s.st_mode)) {
          Dstr dname ((*harmonicsPath)[i]);
          dname += '/';
          DIR *dirp = opendir (dname.aschar());
          if (!dirp)
            xperror (dname.aschar());
          else {
            struct dirent *dp;
	    for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
              Dstr fname (dp->d_name);
	      if (fname == "." || fname == "..")
		continue;
	      else {
                fname *= dname;
                // DO NOT FREE THIS.  It gets pointed to by every station.
                Dstr *qfname = new Dstr(fname);
                doHarmonicsFile (*qfname);
              }
	    }
	    closedir(dirp);
          }
        } else
          doHarmonicsFile ((*harmonicsPath)[i]);
      } else
        xperror ((*harmonicsPath)[i].aschar());
    }
    if (myStationIndex->length() == 0)
      barf (NO_HFILE_PATH);
    myStationIndex->qsort();
  }
  return myStationIndex;
}

void
TideContext::predictText (Station *station, Station::Direction dir,
Timestamp &tm, Dstr &line, Station::EventType &etype, Timestamp *t_out) {
  Timestamp ts;
  PredictionValue pv;
  Dstr etype_desc_long, etype_desc_short, time_print, pv_print;
  station->predictExactTideEvent (tm, dir, ts, etype, etype_desc_long,
    etype_desc_short, pv);
  if (t_out)
    (*t_out) = ts;
  ts.print (time_print, station->timeZone, settings);
  if (!isSunMoonEvent (etype))
    pv.print (pv_print);
  line = time_print;
  line += " ";
  line += pv_print;
  line += "  ";
  line += etype_desc_long;

  // This is replaced by code in text_boilerplate.
#if 0
  // When known, append the direction of currents.  (The offending attributes
  // should be null if it's not a current station.)
  switch (etype) {
  case Station::max:
    if (!(station->maxCurrentAngle.isNull())) {
      line += " ";
      line += station->maxCurrentAngle.ppqdeg(0);
    }
    break;
  case Station::min:
    if (!(station->minCurrentAngle.isNull())) {
      line += " ";
      line += station->minCurrentAngle.ppqdeg(0);
    }
    break;
  default:
    ;
  }
#endif
}

void TideContext::textMode (Station *station, Timestamp start_tm,
Dstr &text_out) {
  Timestamp end_tm = start_tm + Interval(defpredictinterval);
  textMode (station, start_tm, end_tm, text_out);
}

void TideContext::text_boilerplate (Station *station, Dstr &text_out,
int html_form) {
  text_out = (char *)NULL;
  if (html_form)
    text_out += "<h3>";
  text_out += station->name;
  if (html_form)
    text_out += "<br>";
  text_out += '\n';
  if (station->coordinates.isNull())
    text_out += "Coordinates unknown\n";
  else {
    Dstr t;
    station->coordinates.print (t);
    text_out += t;
    text_out += '\n';
  }

  // When known, append the direction of currents.  (The offending attributes
  // should be null if it's not a current station.)
  if (!(station->maxCurrentAngle.isNull())) {
    if (html_form)
      text_out += "<br>";
    text_out += "Flood direction ";
    text_out += station->maxCurrentAngle.ppqdeg(0);
    text_out += '\n';
  }
  if (!(station->minCurrentAngle.isNull())) {
    if (html_form)
      text_out += "<br>";
    text_out += "Ebb direction ";
    text_out += station->minCurrentAngle.ppqdeg(0);
    text_out += '\n';
  }

  // Similarly for notes
  if (!(station->note.isNull())) {
    if (html_form)
      text_out += "<br>Note:&nbsp; ";
    else
      text_out += "Note:  ";
    text_out += station->note;
    text_out += '\n';
  }

  if (html_form)
    text_out += "</h3>";
  text_out += '\n';
}

void TideContext::textMode (Station *station, Timestamp start_tm,
Timestamp end_tm, Dstr &text_out) {
  Dstr line;
  Station::EventType etype;
  Timestamp tm;

  text_boilerplate (station, text_out);

  // Leave a safety margin since these timestamps will generally already
  // be known tide events.
  tm = start_tm - Interval(60);

  // These can come back out of order for subordinate stations.
  struct TideContext::tideline *list = new struct TideContext::tideline;
  list->next = NULL;
  predictText (station, Station::forward, tm, list->text, etype,
    &(list->t_out));
  struct TideContext::tideline *last = list;
  struct TideContext::tideline *tl;
  while (tm < end_tm + Interval(60)) {
    tl = new struct TideContext::tideline;
    last->next = tl;
    last = tl;
    tl->next = NULL;
    predictText (station, Station::forward, tm, tl->text, etype,
      &(tl->t_out));
  }

  // Since this list is _almost_ in order, a bubble sort will be optimal.
  int done = 0;
#ifdef SUPER_ULTRA_VERBOSE_DEBUGGING
  int itctr = 0, swapctr = 0;
#endif
  while (!done) {
#ifdef SUPER_ULTRA_VERBOSE_DEBUGGING
    itctr++;
#endif
    last = list;
    tl = list->next;
    done = 1;
    while (tl) {
      if (last->t_out > tl->t_out) {
        // Swap
        done = 0;
#ifdef SUPER_ULTRA_VERBOSE_DEBUGGING
        swapctr++;
#endif
        Dstr temptext = last->text;
        Timestamp temptout = last->t_out;
        last->text = tl->text;
        last->t_out = tl->t_out;
        tl->text = temptext;
        tl->t_out = temptout;
      }
      last = tl;
      tl = tl->next;
    }
  }
#ifdef SUPER_ULTRA_VERBOSE_DEBUGGING
  cerr << "TideContext::textMode bubble sort took " << itctr <<
    " iterations and " << swapctr << " swaps" << endl;
#endif

  // Yay, we're done.
  while (list) {
    text_out += list->text;
    text_out += '\n';
    last = list;
    list = list->next;
    delete last;
  }
}

void TideContext::calendarMode (Station *station, Timestamp start_tm,
Timestamp end_tm, Dstr &text_out, int html_form, int oldcal) {
  text_boilerplate (station, text_out, html_form);
  Calendar cal (station, start_tm, end_tm);
  Dstr temp;
  cal.print (temp, html_form, oldcal);
  text_out += temp;
}

void TideContext::bannerMode (Station *station, Timestamp start_tm,
Timestamp end_tm, Dstr &text_out) {
  text_boilerplate (station, text_out);
  Banner *banner = bannerFactory (station, settings->tw, start_tm, end_tm);
  Dstr temp;
  banner->drawTides (station, start_tm);
  banner->writeAsText (temp);
  text_out += temp;
  delete banner;
}

void TideContext::statsMode (Station *station, Timestamp start_tm,
Timestamp end_tm, Dstr &text_out) {
  text_boilerplate (station, text_out);
  PredictionValue maxl = station->maxLevel();
  PredictionValue minl = station->minLevel();
  PredictionValue meanl = (maxl + minl) / 2.0;
  Dstr temp;
  text_out += "Mathematical upper bound: ";
  maxl.print (temp);
  text_out += temp;
  text_out += "\nMathematical lower bound: ";
  minl.print (temp);
  text_out += temp;
  text_out += "\n";
  if (station->isCurrent)
    text_out += "Permanent current: ";
  else
    text_out += "Mean Tide Level: ";
  meanl.print (temp);
  text_out += temp;
  text_out += "\n\n";

  int first = 1;
  Timestamp tm = start_tm, maxt, mint;
  while (tm <= end_tm) {
    PredictionValue pv_out;
    Station::EventType etype;
    Dstr etype_desc_long, etype_desc_short;
    Timestamp t_out;
    station->predictExactTideEvent (tm, Station::forward, t_out,
      etype, etype_desc_long, etype_desc_short, pv_out);
    if (tm > end_tm)
      break;
    if (!isSunMoonEvent (etype)) {
      if (first || (pv_out < minl)) {
	mint = t_out;
	minl = pv_out;
      }
      if (first || (pv_out > maxl)) {
	maxt = t_out;
	maxl = pv_out;
      }
      first = 0;
    }
  }

  Dstr timezone = station->timeZone;
  text_out += "Searched interval from ";
  start_tm.print (temp, timezone, settings);
  text_out += temp;
  text_out += " to ";
  end_tm.print (temp, timezone, settings);
  text_out += temp;
  text_out += "\n";
  if (!first) {
    text_out += "Max was ";
    maxl.print (temp);
    text_out += temp;
    text_out += " at ";
    maxt.print (temp, timezone, settings);
    text_out += temp;
    text_out += "\n";
    text_out += "Min was ";
    minl.print (temp);
    text_out += temp;
    text_out += " at ";
    mint.print (temp, timezone, settings);
    text_out += temp;
    text_out += "\n";
  } else {
    text_out += "Found no tide events.\n";
  }
}

void
TideContext::rareModes (Station *station, Timestamp start_tm, Timestamp end_tm,
		      Interval step, Dstr &text_out, int cook_time) {
  text_out = (char *)NULL;
  assert (step > Interval(0));
  assert (start_tm <= end_tm);
  for (Timestamp t = start_tm; t <= end_tm; t += step) {
    if (cook_time) {
      Dstr time_print;
      t.print (time_print, station->timeZone, settings);
      text_out += time_print;
    } else
      text_out += t.timet();
    text_out += " ";
    text_out += station->predictApproximate(t).val();
    text_out += "\n";
  }
}

void TideContext::listModePlain (Dstr &text_out) {
  text_out = "Location list generated ";
  Timestamp now ((time_t)(time(NULL)));
  Dstr tempnow, tz;
  tz = "UTC0";
  now.print (tempnow, tz, settings);
  text_out += tempnow;
  text_out += "\n\n";
  int namewidth = (int)(settings->tw) - 28;
  if (namewidth < 10)
    namewidth = 10;
  StationIndex *si = stationIndex();
  char fmt[80];
  sprintf (fmt, "%%-%d.%ds %%-3.3s %%-23.23s\n", namewidth, namewidth);
  char *buf = (char *) malloc (settings->tw + 30);
  for (unsigned i=0; i<si->length(); i++) {
    Dstr styp, c;
    if ((*si)[i]->is_reference_station())
      styp = "Ref";
    else
      styp = "Sub";
    (*si)[i]->coordinates.print (c, 1);
    sprintf (buf, fmt, (*si)[i]->name.aschar(), styp.aschar(), c.aschar());
    text_out += buf;
  }
  free (buf);
}

void
TideContext::startLocListHTML (Dstr &d) {
  d += "<p><table>\n<tr><th>Location</th><th>Type</th>\n\
<th>Coordinates</th></tr>";
}

void
TideContext::endLocListHTML (Dstr &d) {
  d += "</table></p>\n";
}

void
TideContext::listLocationHTML (Dstr &d, StationRef *sr) {
  assert (sr);
  d += "<tr><td>";
  d += sr->name;
  d += "</td><td>";
  if (sr->is_reference_station())
    d += "Ref";
  else
    d += "Sub";
  d += "</td><td>";
  Dstr tempc;
  sr->coordinates.print (tempc);
  d += tempc;
  d += "</td></tr>\n";
}

void TideContext::listModeHTML (Dstr &text_out) {
  text_out = "<p> Location list generated ";
  Timestamp now ((time_t)(time(NULL)));
  Dstr tempnow, tz;
  tz = "UTC0";
  now.print (tempnow, tz, settings);
  text_out += tempnow;
  text_out += "</p>\n\n";
  StationIndex *si = stationIndex();
  startLocListHTML (text_out);
  for (unsigned i=0; i<si->length(); i++) {
    listLocationHTML (text_out, (*si)[i]);
    if ((i % maxhtmltablen == 0) && (i != 0)) {
      endLocListHTML (text_out);
      startLocListHTML (text_out);
    }
  }
  endLocListHTML (text_out);
}