-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpxconv
More file actions
executable file
·2971 lines (2714 loc) · 151 KB
/
Copy pathgpxconv
File metadata and controls
executable file
·2971 lines (2714 loc) · 151 KB
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
################################################################################
# GPX track converter: post-process routes and tracks produced by GPS loggers etc.
#
# Reads from file(s) given as argument or STDIN and writes to STDOUT or a file.
# Concatenates segments of multiple given tracks or routes (sequential composition),
# using (header) metadata of the first track, preserving segments, and collecting waypoints.
# Optionally augments main input by merging data from alternative input (from parallel tracks),
# ignoring metadata and segment information of the alternative input.
#
# Reports statistics including total length and time, moving time, average moving speed and max speed,
# min and max altitude, total ascent and descent, as well as max ascent and descent rate.
# Reports missing data and by default ignores points containing implausible data w.r.t.
# altitude, ascent/descent rate, speed, acceleration/deceleration, and direction change.
# Between segments and on start/end of merged sections, speed and ascent/descent rate are ignored.
# Corrects implausible elevation gain/loss after gaps, typically on exit of tunnel or building
# Optionally filters out points before or after given time limits.
# Optionally filters out points with an element value below or above given limits.
# Optionally reduces output size by removing points that are rather close-by or on rather straight line.
# Optionally prunes comments, extensions, or extension elements with value below or above given limits.
# By default carries over missing altitude and time data between segments.
# By default fills in missing altitude and time data by interpolation within segments.
# By default inserts interpolated points in long time gaps (default 1800 seconds sufficient for exiftool).
# Optionally smoothens tracks.
# Optionally corrects elevation w.r.t. geoid height (= ellipsoidal - orthometric height).
# Optionally produces additional statistics on a per-segment or per-day basis.
# Optionally analyzes climbing phases with extra ascent/descent and speed statistics.
# Optionally calculates approximate total energy spent by biking along the resulting track.
# Prints information and warnings (unless disabled), as well as any errors, to STDERR.
#
use constant TOOL_NAME => "GPXConv";
use constant TOOL_VERSION => "2.9.3";
my $TOOL_ID = TOOL_NAME." v".TOOL_VERSION;
use constant MIN_INPUT_TIMEDIFF => 2;
my $usage =
"Usage: gpxconv <option(s) and infile(s)> [> <outfile>] [2> <logfile>]
Command-line options:
-h | -help | --help - print these hints and exit
-version - print tool name and version and exit
-swim, -walk, -cycle, -drive, -fly - type of recorded activity, default: drive
-no_sanitize - do not sanitize trackpoints with implausible data
-no_insert - do not insert trackpoints on long time gaps
-smooth - smoothen tracks
-phases - analyze and provide statistics for ascent/descent phases
-segs [<n>..[<m>][(+|-)<d>]] - add statistics per segment n..m, may adapt indexes +/-d
-days [<n>..[<m>][(+|-)<d>]] - add statistics per day n..m, may adapt indexes +/-d
-tz <hours> - offset from UTC (timezone+DST) for -days, default taken from system
-split <basename> - produce GPX files per day or segment, with name <basename>_<i>.gpx
-lean_stat_wpts - only one stat. wpt per segment/day with data except ascent/descent
-info_wpts - provide info points also in the form of waypoints
-warn_wpts - provide warning points also in the form of waypoints
-cmt_wpts <pattern> - add info waypoints for trackpoints with matching 'cmt' element
-src_wpts <pattern> - add warning waypoints for trackpoints with matching 'src' element
-merge <file> - augment tracks in infile(s) with data from given alternative file
-weight <value> - calculate biking energy for given weight in kg
-begin <time> - ignore points before given time
-end <time> - ignore points after given time
-resolution <seconds> - minimum time difference between trackpoints on input, default: ".MIN_INPUT_TIMEDIFF."
-min <name> <limit> - filter out points with element value below limit
-max <name> <limit> - filter out points with element value above limit
-min_ext <name> <limit> - prune extension elements with value below limit
-max_ext <name> <limit> - prune extension elements with value above limit
-min_dist <meters> - output only points that have at least the given distance
-min_angle <degree> - output only points after at least the given deviation angle
-prune_wpts - remove waypoints
-prune_cmts - remove comments
-prune_exts - remove extensions
-ni - do not output information
-nw - do not output warnings
-o <outfile> - output the resulting track to <outfile>
-debug - enable internal consistency checks and debug output
Other options can be set by changing values of the configuration variables.
(c) 2012-2025 David von Oheimb - License: MIT - ".TOOL_NAME." version ".TOOL_VERSION;
################################################################################
use strict;
use warnings;
# use feature 'signatures'; # https://perldoc.perl.org/perlsub#Signatures
### configuration variables
my $activity = "-drive"; # default
# basic output control
use constant PRUNE_WPTS => 0; # by default do not ignore waypoints
use constant PRUNE_AUTOMATIC_WPTS => 1; # ignore waypoints containing <name><!\[CDATA\[((day )?\d+)?\]\]></name> as produced by OruxMaps
use constant PRUNE_CMTS => 0; # by default do not remove comments
use constant PRUNE_DESCS => 0; # do not remove descriptions
use constant PRUNE_LINKS => 0; # do not remove links
use constant PRUNE_EXTENSIONS => 0; # by default do not remove extensions
use constant PRUNE_RECORDED_SPEED => 1; # remove existing speed extensions with recorded speed (<gpxtpx:speed>)
use constant INCLUDE_SPEED => 1; # include our simple speed extensions with recorded or computed speed (<speed>)
use constant DISABLE_TRKPT_CMT => 0; # do not add 'cmt' entries to trackpoints, e.g., comments on ignored points
use constant DISABLE_TRKPT_SRC => 0; # do not add 'src' entries to trackpoints, e.g., on time gaps and interpolated data
use constant DISABLE_TRKPT_FIX => 0; # do not add 'fix' entries to trackpoints, on points inserted with interpolated data
# control filling in missing altitude and/or time
use constant CARRY_OVER_ELE => 1; # copy missing altitude from end of previous segment or begin of following segment # better not: last available value (prev_avail_ele)
use constant CARRY_OVER_TIME => 1; # copy missing time from end of previous segment or begin of following segment
use constant FILL_MISSING_ELE => 1; # interpolate missing altitude
use constant FILL_MISSING_TIME => 1; # interpolate missing time
# control use of recorded vs. computed speed
use constant MAX_TIMEDIFF_RECORDED_SPEED => 2; # maximum number of seconds for which recorded speed is used
# analysis control
use constant MIN_SPEED_MOVING => 1; # threshold for detecting movement (in km/h)
use constant ANALYZE_PHASES => 0; # by default do not analyze ascent/descent phases
use constant ELE_THRESHOLD => 25; # threshold for detecting/accepting ascent or descent (in m);
# should be larger than short-term altitude measurement error
my $PHASES_REPORT_THRESHOLD = ELE_THRESHOLD; # default
# merge control
use constant MERGE_MIN_GAP => 20; # minimum gap duration in seconds for starting to switch to alternative input
use constant MERGE_MIN_MORE => 7; # minimum number of more points on alternative input to allow switching to it
use constant MERGE_WARN_DIST => 100; # warn if first point of merged portion is more than given number of meters away from regular track
# smoothing control
use constant ENABLE_SMOOTHING => 0; # by default disable smoothing
use constant SMOOTHING_MAX_GAP => 60; # maximum number of seconds between trackpoint to be smoothened and its neighbors
# control insertion of points within long time gaps
my $insert_points = 1; # whether to enable inserting points with interpolated data in long time gaps
use constant INSERT_SEGMENT => 0; # enable inserting segment for long time gaps just before segment start
use constant INSERTION_MAX_GAP => 1800; # length of gap in seconds between consecutive trackpoints before
# insertion should be used (1800 for exiftool default GeoMaxIntSecs; for TrailGuru 3600 would be sufficient)
# info warning output control
my $output_info = 1; # whether outputting information is enabled
my $output_warnings = 1; # whether outputting warnings is enabled
my $info_wpts = 0; # whether to output information points in addition as waypoints
my $warn_wpts = 0; # whether to output warning points in addition as waypoints
my $cmt_wpts = ""; # pattern to match for adding info waypoints for trackpoints with matching 'cmt' element
my $src_wpts = ""; # pattern to match for adding wanrning waypoints for trackpoints with matching 'src' element
use constant WARNING_TPT_DIST => 2000; # threshold for trackpoint distance warning (in meters)
use constant WARNING_WPT_DIST => 100; # threshold for waypoint distance warning (in meters)
use constant MAX_SPEED_DEVIATION => 0.25; # threshold for speed measuring deviation warning (fraction of MAX_PLAUSIBLE_SPEED)
# using absolute value for MAX_SPEED_DEVIATION because we compute speed from absolute values (coordinates and time)
# sanitization control
use constant SANITIZE_TRKPTS => 1; # whether trackpoint sanitization is enabled by default
my $sanitize = SANITIZE_TRKPTS;
my $MIN_TIMEDIFF ; # in seconds
my $MAX_PLAUSIBLE_SPEED ; # maximal speed in km/h
my $MAX_PLAUSIBLE_ACCEL ; # maximal acceleration m/s/s
my $MAX_PLAUSIBLE_DECEL ; # maximal deceleration m/s/s
my $MAX_PLAUSIBLE_ELE_GAIN; # maximal ascent rate in m/h
my $MAX_PLAUSIBLE_ELE_LOSS; # maximal descent rate in m/h
use constant MIN_TUNNEL_GAP => 20; # threshold for assuming exit of tunnel or building before elevation gain/loss correction (in seconds)
use constant MAX_PLAUSIBLE_ANGLE_DIFF => 170; # maximal plausible turning angle above speed threshold
use constant MAX_PLAUSIBLE_ANGLE_SPD_THRESHOLD => 15; # speed threshold for maximal plausible turning angle in km/h
use constant MIN_PLAUSIBLE_ELE => -450; # minimal plausible altitude; actual elevation values on Earth may be as low as -450 m at Dead Sea
# time control
use constant TIME_CORRECTION => 0; # number of seconds to add to time stamps in trkpt and wpt
my $MAX_UNDEF_TIME = str_to_epoch("9999-12-31T23:59:59Z"); # as used in RFC 5820 section 4.1.2.5
# elevation correction control
use constant GEOID_ELE_CORRECTION => 0; # whether to correct elevation wrt. geoid height retrieved online
use constant DEFAULT_ELE_CORRECTION => 0; # 47; # if used should be -(average geoid height)
### other constants
use constant H2S => 3600 ; # factor for converting hours to seconds
use constant M2KM => 0.001; # factor for converting m to km
use constant MPS2KMPH =>H2S * M2KM;# factor for converting m/s to km/h
use constant METERS_PER_DEGREE_LAT => 111133; # at 45 degrees, cf. https://en.wikipedia.org/wiki/Latitude#Length_of_a_degree_of_latitude
use constant LAT_PRECISION => "%.5f"; # latitude resolution = 0.00001 degrees (<= 1.11 meters)
use constant LON_PRECISION => "%.5f"; # longitude resolution = 0.00001 degrees (<= 1.11 meters)
use constant ELE_PRECISION => "%5.0f"; # altitude resolution = 1 meters
use constant ELE_PRECISION0 => "%.0f";
use constant ELE_PRECISION3 => "%.3f";
use constant DIF_PRECISION => "%+5.0f"; # altitude difference resolution = 1 meters
use constant SLOPE_PRECISION=> "%2.0f"; # slope resolution = 1 %
use constant RAT_PRECISION => "%+5.0f"; # altitude ascent/descent rate resolution = 1 meters
use constant RAT_PRECISION2 => "%+6.0f"; # altitude ascent/descent rate resolution = 1 meters
use constant DIS_PRECISION => "%.3f"; # distance resolution = 0.001 km
use constant DIS_PRECISION2 => "%6.3f"; # distance resolution = 0.001 km
use constant SEC_PRECISION => "%.0f"; # seconds resolution = 1 second
use constant SPD_PRECISION => "%4.0f"; # speed resolution = 1 km/h
use constant AVG_PRECISION => "%.1f"; # avg speed resolution = 0.1 km/h
use constant SPD_PRECISION0 => "%.0f";
use constant ACC_PRECISION => "%.1f"; # acceleration resolution = 0.1 m/s/s
use constant EMOJI_PREFIX => ""; # or "emoji-" for GAIA GPS
# trkpt flags
use constant DUPLICATED_POINT => 1 << 0; # no more actually uused
use constant INSERTED_POINT => 1 << 1; # its use could be removed
use constant INTERPOLATED_ELE => 1 << 2;
use constant INTERPOLATED_TIM => 1 << 3;
use constant SUBSTITUTED_ELE => 1 << 4;
use constant SUBSTITUTED_TIM => 1 << 5;
use constant COMPUTED_SPEED => 1 << 6;
use constant CORRECTED_ELE => 1 << 7;
use constant START_MERGE => 1 << 8;
use constant PAUSE_MERGE => 1 << 9;
use constant STATISTICS_WPT => 1 <<10; # used to prevent removal on pruning trkpts
# global option variables with related num_* state variables
my $debug = 0;
my $merge;
my $num_ignored_diff = 0;
my $num_ignored_hdrs = 0;
my $begin_sec;
my $num_ignored_before = 0;
my $end_sec;
my $min_input_timediff = MIN_INPUT_TIMEDIFF;
my $num_ignored_after = 0;
my $max_elem;
my $max_elem_limit;
my $num_elem_above = 0;
my $min_elem;
my $min_elem_limit;
my $num_elem_below = 0;
my $max_ext;
my $max_ext_limit;
my $num_ext_above = 0;
my $min_ext;
my $min_ext_limit;
my $num_ext_below = 0;
my $min_dist;
my $num_removed_min_dist = 0;
my $min_angle;
my $num_removed_min_angle = 0;
my $num_points_output = 0;
my $ele_corr = DEFAULT_ELE_CORRECTION;
my $smoothing = ENABLE_SMOOTHING;
my $num_smoothened = 0;
my $phases = ANALYZE_PHASES;
my $weight;
my $prune_wpts = PRUNE_WPTS;
my $num_pruned_wpts = 0;
my $num_auto_wpts = 0;
my $prune_cmts = PRUNE_CMTS;
my $num_pruned_cmts = 0;
my $num_pruned_descs = 0;
my $num_pruned_links = 0;
my $prune_exts = PRUNE_EXTENSIONS;
my $num_pruned_exts = 0;
# trackpoint data from regular infile(s), followed by data from alternative input
# array with doubly linked list structure for efficient element insertion and deletion
my @PREV; # index of point before (initially current index - 1)
my @NEXT; # index of point after (initially current index + 1)
sub PREV { return defined $_[0] ? $PREV[$_[0]] : undef; }
sub NEXT { return defined $_[0] ? $NEXT[$_[0]] : undef; }
my @TXT; # text (containing trkpt output) to prepend when printing
my @IGN; # number of points ignored immediately before this one
my @SEG;
my @FLG;
my @LAT;
my @LON;
my @ELE; # or "" if not available
my @TIM; # or "" if not available
my @SEC; # computed from @TIM, possibly adapted, or undefined if not available
my @DIS2;# square sum of the LAT and COS(LAT)*LON differences from point before, 0 for first point
my @DIS; # derived from LAT and LON, and ELE if available, also from point before, 0 for first point
my @ANG; # horizontal direction change (i.e., turning angle) between last, current, and next point, undef if not available
my @DIR; # the direction arriving at each point from the previous one, undef if not (yet) computed or invalidated
my @SPD; # as recorded or computed (average from previous point if FLG contains COMPUTED_SPEED), or "" if not available
my @CMT; # as given in input but without <cmt> and </cmt> tags, or "" if not available
my @SRC; # as given in input but without <src> and </src> tags, or "" if not available
my @FIX; # as given in input but without <fix> and </fix> tags, or "" if not available
my @EXT; # or "" if not available
# waypoint data
my @WLAT;
my @WLON;
my @WELE; # or "" if not available
my @WTIM; # or "" if not available
my @WSEC; # computed from @WTIM, possibly adapted, or undefined if not available
my @WTXT; # inner waypoint text after </time>, or "" if not available
my @WSTR; # for diagnostics only: full original but indented waypoint text surrounded by '...', or undefined for statistics waypoint
my @WIDX; # index of trkpt related to this wpt belongs, or -1
# ascent/descent phase data
my @PHASE_DURATION;
my @PHASE_DIFF;
my @PHASE_DIST;
my @PHASE_SPD;
my @PHASE_RATE;
my @PHASE_MAX_SPD_INDEX;
my @PHASE_MAX_RATE;
my @PHASE_MAX_RATE_INDEX;
my @PHASE_END_INDEX;
my $ascent__phases_suppressed = 0;
my $descent_phases_suppressed = 0;
# global state variables
my $HEAD;
my @NAME;
my $found_corr = 0;
my $num_merges = 0;
my $num_merged_points = 0;
my $num_skip_points = 0;
my $num_merged_points_last = 0;
my $num_skip_points_last = 0;
my $min_lat, my $max_lat;
my $min_lon, my $max_lon;
my ($min_sec, $max_sec);
my ($min_tim, $max_tim) = ("", ""); # $max_tim is not really used
my ($tz, $sec_offset);
my ($segs, $days);
my ($part_start, $part_end, $part_offset);
my $split;
my $lean_stat_wpts = 0;
# the following arrays hold statistic data per part, with index ($part_start - 1) holding the overall values
my (@MAX_SPD , @MIN_ELE , @MAX_ELE , @MAX__ASC, @MAX_DESC , @MAX_GAIN , @MAX_LOSS );
my (@MAX_SPD_INDEX, @MIN_ELE_INDEX, @MAX_ELE_INDEX, @MAX__ASC_INDEX, @MAX_DESC_INDEX, @MAX_GAIN_INDEX, @MAX_LOSS_INDEX);
my (@LAST_GAIN_INDEX, @LAST_LOSS_INDEX, @PART_START_INDEX, @PART_END_INDEX);
my (@SUM__ASCENT, @TIME__ASCENT, @MISSING__ASCENT_TIME,
@SUM_DESCENT, @TIME_DESCENT, @MISSING_DESCENT_TIME);
my (@SUM_DIS, @SUM_DIS_MOV, @SUM_TIMEDIFF_MOV, @DURATION);
# for calculating relative deviation between recorded and computed speed
my $sum_speed = 0;
my $sum_speed_deviation = 0;
my $sum_energy = 0;
my $out = *STDOUT; # https://stackoverflow.com/questions/10478884/are-there-rules-which-tell-me-what-form-of-stdout-stderr-sdtin-i-have-to-choose
### various subprocedures
#http://www.perlmonks.org/?node_id=406883
#sub max { return $_[0] > $_[1] ? $_[0] : $_[1]; }
use List::Util qw[min max];
# http://stackoverflow.com/questions/178539/how-do-you-round-a-floating-point-number-in-perl
use Math::Round qw(nearest);
use Math::Trig qw(deg2rad pi2); # use Math::Trig 'great_circle_distance';
use constant RAD2DEG => 360 / pi2;
use File::Temp qw(tempfile);
# use DateTime::Format::ISO8601;
use Time::ParseDate ();
# use Time::PrintDate;
use Time::gmtime qw(gmtime);
use Scalar::Util qw(looks_like_number);
sub print_line { print STDERR "$_[0]\n"; }
sub warning {
print_line("WARNING: $_[0]") if $output_warnings;
}
sub info {
print_line("INFO : $_[0]") if $output_info;
}
sub abort {
print_line("$_[0]\naborting");
exit 1;
}
sub debug {
print_line("### DEBUG: $_[0]");
}
sub debug_log {
print_line("### LOG: $_[0]") if $debug;
}
# https://stackoverflow.com/questions/229009/how-can-i-get-a-call-stack-listing-in-perl
# alternatively to making explicit individual calls to stacktrace, may use: perl -d:Confess
sub stacktrace {
use Devel::StackTrace;
print_line("");
debug(Devel::StackTrace->new->as_string);
# { # further alternative:
# use Carp qw<longmess>;
# # local $Carp::CarpLevel = -1;
# debug longmess();
# }
# { # further alternative:
# for (print STDERR "Stack Trace:\n", my $i = 0; my @call_details = caller($i); $i++) {
# print STDERR $call_details[1].":".$call_details[2]." in function ".$call_details[3]."\n";
# }
# }
}
# str_to_epoch("1970-01-01T00:00:00Z") = 0; returns undef on error
# due to parsedate(), allows for weird values, e.g., 2000-01-01T00:00:63Z is taken as 2000-01-01T00:01:03Z
sub str_to_epoch {
stacktrace() unless $_[0] eq '' || $_[0];
my $s = $_[0];
return undef unless $s =~ m/^\d{2,4}-\d{1,2}-\d{1,2}(T(\d{1,2}(:\d{1,2}(:\d{1,2}(\.\d{1,})?)?)?)?)?\s*([A-Z]+|[+-]\d+)$/; # pre-parse because parsedate() is not very strict
# within a day, may use: seconds + 60 * (minute + 60 * hour)
# return DateTime::Format::ISO8601->parse_datetime($s)->epoch();
# # not used due to Perl library bug on Mac OS X: "dyld: lazy symbol binding failed: Symbol not found: _Perl_newSVpvn_flags"
# # http://www.en8848.com.cn/Reilly%20Books/perl3/cookbook/ch03_08.htm
# use Time::Local;
# $date is "1998-06-03" (YYYY-MM-DD form).
# ($yyyy, $mm, $dd) = ($date =~ /(\d+)-(\d+)-(\d+)/;
# # calculate epoch seconds at midnight on that day in this timezone
# $epoch_seconds = timegm(0, 0, 0, $dd, $mm, $yyyy);
$s =~ s/-/\//g;
$s =~ s/(T\d+)Z/$1:00Z/; # workaround for the case that only hour is given
$s =~ s/T/ /;
$s =~ s/Z/+0000/;
my $sec = Time::ParseDate::parsedate($s);
$sec += $1 if defined $sec && $s =~ m/:\d\d(\.\d+)/; # fractional seconds
return $sec;
}
sub epoch_to_str {
stacktrace() unless defined $_[0];
# use DateTime; # not used due to Perl library bug on Mac OS X:
# "dyld: lazy symbol binding failed: Symbol not found: _Perl_newSVpvn_flags"
# my $dt = DateTime->from_epoch(epoch => $_[0]);
# return $dt->ymd."T".$dt->hms."Z";
#use Date::Manip qw(ParseDate UnixDate);
#$date = ParseDate("18 Jan 1973, 3:45:50");
# return UnixDate($_[0], "%Y-%m-%dT%H:%M:%SZ");
my $sec = shift;
my $millisec = nearest(.001, $sec - int($sec)); # fractional seconds
my $millisecs = substr(substr($millisec, 1)."00", 0, 4);
my $tm = gmtime($sec);
return sprintf(
"%04d-%02d-%02dT%02d:%02d:%02d%sZ",
$tm->year + 1900,
$tm->mon + 1,
$tm->mday, $tm->hour, $tm->min, $tm->sec,
$millisecs eq "00" ? "" : $millisecs);
}
sub round_tim { # round to nearest second
stacktrace() unless $_[0];
my $tim = shift;
# $tim =~ s/(:\d\d)(\.\d+)/$1/; # strip fractional seconds
return $tim =~ m/\.(\d+)Z$/ && $1 != 0 ? epoch_to_str(nearest(1, str_to_epoch($tim))) : $tim;
}
sub timediff_str {
stacktrace() if !defined $_[1] || $_[1] eq "";
my $t = $_[1] + 0.5; # for rounding to nearest second
my $s = $t % 60;
$t = ($t - $s) / 60;
my $m = $t % 60;
$t = ($t - $m) / 60;
return sprintf($_[0].":%02d:%02d h", $t, $m, $s);
}
sub timediff_string { return timediff_str("%d", $_[0]); }
sub ele_string {
my ($len, $ele) = @_;
stacktrace() if !defined $ele || $ele eq "";
$ele = (sprintf ELE_PRECISION0, $ele) =~ s/^\s*-(0(\.0*)?)$/$1/r if $len >= 0;
return (" " x max(0, abs($len) - length($ele))) . $ele;
}
sub dis_str {
stacktrace() if !defined $_[1] || $_[1] eq "";
return sprintf $_[0]." km", M2KM * $_[1];
}
sub dis_string { return dis_str(DIS_PRECISION, $_[0]); }
sub point_str {
my $i = $_[0];
return "point $i: ". ($TIM[$i] ne ""
? "tim=$TIM[$i]"
: "($LAT[$i], $LON[$i], ".($ELE[$i] eq "" ? "none" : $ELE[$i]).")");
}
sub spd_or_none { return $_[0] eq "" ? "none" : (sprintf "%.3f", MPS2KMPH * $_[0]) =~ s/\.?0+$//r; }
my $spd_prec_len = 1; # used only for spd_string
sub spd_full {
stacktrace() if !defined $_[0] || $_[0] eq "";
return sprintf SPD_PRECISION, MPS2KMPH * $_[0];
}
sub spd_str {
stacktrace() if !defined $_[0] || $_[0] eq "";
return sprintf SPD_PRECISION0, MPS2KMPH * $_[0];
}
sub spd_string {
my $s = spd_str($_[0]);
return " " x ($spd_prec_len - length($s)) . $s;
}
# used only for formatting:
my $lat_prec_len = my $lat_full_len = lat_str(0);
my $lon_prec_len = my $lon_full_len = lon_str(0);
my $ele_prec_len = my $ele_full_len = length((sprintf ELE_PRECISION0, 0));
my $tim_len = length(epoch_to_str(0));
sub lat_str { return (sprintf LAT_PRECISION, $_[0]) =~ s/^\s*-(0(\.0*)?)$/$1/r; }
sub lon_str { return (sprintf LON_PRECISION, $_[0]) =~ s/^\s*-(0(\.0*)?)$/$1/r; }
sub lat_string {
my $s = lat_str($_[0]);
return " " x max(0, $lat_prec_len - length($s)) . $s;
}
sub lon_string {
my $s = lon_str($_[0]);
return " " x max(0, $lon_prec_len - length($s)) . $s;
}
my $bride_gap_insert_txt = "bridging time gap: inserted point";
my $bride_gap_duplicate_txt = "bridging time gap: duplicated point ";
sub parse_point {
my $str = $_[0];
my $is_trkpt = $str =~ m/^<trkpt /;
my $lat, my $lon;
abort("FATAL: cannot find lat/lon part of point: $_[0]")
unless $str =~ s#^(<\w+)(\s+(\w+\s*=\s*"[^\"]*"\s*)+)\s*>#$1>#s;
my $lat_lon_str = $2;
if ($lat_lon_str =~ m#\slat\s*=\s*"(-?\d*(\.\d+)?)"\s*lon\s*=\s*"(-?\d*(\.\d+)?)"#s) {
($lat, $lon) = ($1, $3);
} elsif ($lat_lon_str =~ m#\slon\s*=\s*"(-?\d*(\.\d+)?)"\s*lat\s*=\s*"(-?\d*(\.\d+)?)"#s) {
($lat, $lon) = ($3, $1);
} else {
abort("FATAL: error parsing lat/lon part '$lat_lon_str' of point: $_[0]");
}
$lat_full_len = max($lat_full_len, length($lat));
$lon_full_len = max($lon_full_len, length($lon));
my $ele_str = my $ele = "";
if ($str =~ s#[ \t]*(<ele>\s*([^\s<]*)\s*</ele>)\n?##s) {
($ele_str, my $ele_inner) = ($1, $2);
abort("FATAL: error parsing elevation value '$ele_inner' in point: $_[0]")
unless $ele_inner =~ m/^\s*(-?\d*(\.\d+)?)(\.\d*)?\s*$/; # ignores any decimals past any second decimal dot, e.g, takes ".12" on ".12.34" input
$ele = $1; # may be empty or 0
$ele_prec_len = max($ele_prec_len, length((sprintf ELE_PRECISION0, $ele)));
$ele_full_len = max($ele_full_len, length($ele));
}
my $tim = "", my $sec;
if ($str =~ s#[ \t]*(<time>\s*([^\s<]*)\s*</time>)\n?##s) {
$tim = my $orig_tim = $2;
$tim =~ s/\.0+Z/Z/;
$tim_len = max($tim_len, length($tim));
$sec = str_to_epoch($tim);
$sec = 0 if $orig_tim eq "NO" || $orig_tim eq "NO_TIME" || $orig_tim =~ m/^\s*$/;
abort("FATAL: error parsing time value '$orig_tim' in point: $_[0]")
unless defined $sec;
$sec += 0.001 if $tim =~ m/\.999Z/; # for some reason, at least OruxMaps on Android often reports 0.001 seconds less than a full second
if (TIME_CORRECTION) {
$sec += TIME_CORRECTION;
$tim = epoch_to_str($sec);
} else {
$tim =~ s/(T\d\d)Z/$1:00Z/;
$tim =~ s/(T\d\d:\d\d)Z/$1:00Z/;
}
}
$ele = "" if !$ele_str && $tim eq ""; # for routes generated, e.g., using Google My Maps
my $cmt = "";
if ($is_trkpt && !$prune_cmts && $str =~ s#[ \t]*<cmt>\s*(.*?)\s*?</cmt>\r?\n?##s) {
$cmt = $1;
$cmt =~ s#\n##sg;
}
my $src = "";
if ($is_trkpt && $str =~ s#[ \t]*<src>\s*(.*?)\s*?</src>\r?\n?##s) {
$src = $1;
$src =~ s#\r?\n##sg; # TODO match \r? also in other similar situations
}
my $fix = "";
if ($is_trkpt && $str =~ s#[ \t]*<fix>\s*(.*?)\s*?</fix>\r?\n?##s) {
$fix = $1;
$fix =~ s#\r?\n##sg;
}
my $ext = "";
while ($str =~ s#[ \t]*<extensions>(.*?)</extensions>\n?#($ext .= $1, "")#es) {
$ext =~ s#\n##sg;
}
my $spd = "";
if ($is_trkpt && $ext =~ m#<(\w+:)?speed>([^<]*)</(\w+:)?speed>#s) {
abort("FATAL: inconsistent tags '<$1speed>' and '</$3speed>' in speed extension of in point: $_[0]") if ($1 // "") ne ($3 // "");
my ($prefix, $spd_str) = ($1, $2);
abort("FATAL: error parsing speed extension value '$spd_str' in point: $_[0]")
unless $spd_str =~ m/^\s*(-?\d*(\.\d+)?)(\.\d*)?\s*$/; # ignores any decimals past any second decimal dot, e.g, takes ".12" on ".12.34" input
# we assume that recorded speed takes altitude into account (i.e., is not just horizontal/lateral speed),
# see also https://forums.geocaching.com/GC/index.php?/topic/209525-gps-speed-3d-or-2d/
$spd = $1;
$spd *= 1 / MPS2KMPH unless $prefix; # usually, speed is given m/s, while our abbreviated extension uses km/h
$spd_prec_len = max($spd_prec_len, length(spd_str($spd))); # used only for spd_string
}
my $rest = $str;
$rest =~ s#\n##sg;
$rest =~ s#>[ \t]+<#><#g;
# clean up potential errors in input:
$rest =~ s#<ele></ele>##;
$rest =~ s#<time></time>##;
my $ignore = 0;
$ignore = 1 if
(diff_defined($sec, $begin_sec) // 0) < 0 && ++$num_ignored_before ||
(diff_defined($sec, $end_sec) // 0) > 0 && ++$num_ignored_after ||
$max_elem && $_[0] =~ m#<$max_elem>\s*(-?[\.\d]+)\s*</$max_elem>#s && $1 > $max_elem_limit && ++$num_elem_above ||
$min_elem && $_[0] =~ m#<$min_elem>\s*(-?[\.\d]+)\s*</$min_elem>#s && $1 < $min_elem_limit && ++$num_elem_below ||
# silently ignore any point inserted or duplicated by earlier run of this tool:
($src =~ m#^^($bride_gap_insert_txt|$bride_gap_duplicate_txt(after|before))$# && $fix eq "none");
return ($lat, $lon, $ele, $tim, $sec, $spd, $rest, $cmt, $src, $fix, $ext, $ignore);
}
sub plural { my ($n, $str) = @_; return "$n $str".($n == 1 ? "" : "s"); }
sub points { return plural ($_[0], "point"); }
sub info_trkpt {
stacktrace() unless defined $_[1];
print_trkpt(shift @_, "INFO : " . shift @_, @_) if $output_info;
}
sub warn_trkpt {
stacktrace() unless defined $_[1];
print_trkpt(shift @_, "WARNING: " . shift @_, @_) if $output_warnings;
}
sub abort_trkpt {
stacktrace() unless defined $_[1];
print_trkpt(shift @_, "FATAL: " . shift @_, @_);
}
sub print_trkpt {
stacktrace() unless defined $_[0];
my ($i, $head, $tail, $lat, $lon, $ele, $tim, $sec) = @_;
# $head may be empty, $tail may be empty or undef
$tail = " ".$tail if $tail && !($tail =~ m/^;/);
($lat , $lon , $ele , $tim , $sec ) =
($LAT[$i], $LON[$i], $ELE[$i], $TIM[$i], $SEC[$i]) if $i >= 0;
stacktrace() if (!defined $lat || !defined $lon || !defined $ele || !defined $tim);
# using original precision here for better traceability
# $lat = lat_str($lat);
# $lon = lon_str($lon);
my $elev = $ele;
if ($elev eq "") {
$elev = "NONE";
$ele_prec_len = max($ele_prec_len, length($elev));
$ele_full_len = max($ele_full_len, length($elev));
} elsif ($ele_full_len > $ele_prec_len) {
my $decimals = -1;
$decimals = length($1) if $elev =~ m/\.(\d+)/;
my $n_spaces = $ele_full_len - $ele_prec_len - $decimals - 1;
$elev .= ' ' x $n_spaces if $n_spaces > 0;
}
my $time = $tim eq "NO" ? "" : " ".($tim eq "" ? "NO_TIME" : $tim);
print_line("$head "
. "<trkpt"
. ' lat="' . ($lat . '"' . (' ' x max(0, $lat_full_len - length($lat))))
. ' lon="' . ($lon . '"' . (' ' x max(0, $lon_full_len - length($lon))))
. " <ele>" . ele_string(-$ele_full_len, $elev)
. $time
.($tail ? (" " x max(0, $tim_len + length(" ") - length($time))).$tail : ""));
abort("\n\n\n") if $head =~ "^FATAL:";
$head =~ s|^(INFO)\s*:|$1:|;
$head =~ s/(.*):\s*$/$1/ ||
$head =~ s/the( most recently merged)$/this$1 point/ ||
$head =~ s/(skipping) (regular)$/$1 this $2 point/ ||
$head =~ m/(start|end)\s*$/ ||
$head =~ s/ at$// ||
$head =~ s/$/ this point/;
$tail = "" unless $tail; # enforce output also in case $lean_stat_wpts
add_stat_wpt($i, $head, $tail, undef, $lat, $lon, $ele, $tim, $sec) if $head =~ m|^INFO:| && $info_wpts;
add_stat_wpt($i, $head, $tail, undef, $lat, $lon, $ele, $tim, $sec) if $head =~ m|^WARNING:| && $warn_wpts;
}
sub diff_defined { return defined $_[0] && defined $_[1] ? $_[0] - $_[1] : undef; }
sub diff_nonempty { stacktrace() unless defined $_[0] && defined $_[1];
return $_[0] ne "" && $_[1] ne "" ? $_[0] - $_[1] : undef; }
sub eq_nonempty { return $_[0] eq "" ? $_[1] eq ""
: $_[1] eq "" ? $_[0] eq "" : $_[0] == $_[1] }
sub section { return ($FLG[$_[0]] & (START_MERGE | PAUSE_MERGE)) != 0 } # switched between regular and merged track
sub rate { return defined $_[0] && $_[1] ? H2S * $_[0] / $_[1] : ""; } # ascent/descent rate in m/h
sub recalculate_DIS {
my ($i, $const_2d) = @_;
my $prev_i = PREV($i);
return if !defined $prev_i || $SEG[$i];
$DIS2[$i] = sq_distance_2d($LAT[ $i], $LON[ $i],
$LAT[$prev_i], $LON[$prev_i]) unless $const_2d;
$DIS[$i] = distance_3d($DIS2[$i], $ELE[$i], $ELE[$prev_i]);
}
sub recalculate_SPD {
my $i = $_[0];
return if !defined PREV($i) || $SEG[$i] || section($i) || !($FLG[$i] & COMPUTED_SPEED);
my $diff_time = diff_defined($SEC[$i], $SEC[PREV($i)]);
$SPD[$i] = $DIS[$i] / $diff_time if $diff_time;
}
sub recalculate_all {
my ($i, $old_i) = @_;
$DIR[$i] = undef; # invalidate cached direction
my $const_2d = defined $old_i &&
($old_i == $i || $LAT[$old_i] == $LAT[$i] && $LON[$old_i] == $LON[$i]);
recalculate_DIS($i, $const_2d);
recalculate_SPD($i);
}
#my @COS2; # approximation of cos(2phi) for efficiency
#for (my $phi2 = 0; $phi2 <= 180; $phi2++) {
# $COS2[-$phi2] = $COS2[$phi2] = abs(cos(deg2rad(($phi2 + 1) / 2)));
# # error in cos(deg2rad(($phi2 / 2))) - $COS2[$phi2]
# # max absolute error is < 0.0088
# # max relative error is < 0.027 for latitudes below North Cape
#}
# https://stackoverflow.com/questions/639695/how-to-convert-latitude-or-longitude-to-meters
my @COS;
sub sq_distance_2d {
my ($lat, $lon, $lat2, $lon2) = @_;
my $diff_lat = ($lat - $lat2) * METERS_PER_DEGREE_LAT;
return $diff_lat * $diff_lat if $lon == $lon2; # optimization in special case, no need to use cos()
# with the following two approximations, cache hit rate is around 90% and resulting error is rarely more than a meter:
my $mean_lat = ($lat + $lat2) / 2;
# cosine cache input resolution 0.0001 deg corresponding to < 10 meters:
my $rounded_scaled_abs_mean_lat = ($mean_lat < 0 ? -$mean_lat : $mean_lat) * 10000 + 0.5;
my $diff_lon = ($lon - $lon2) * METERS_PER_DEGREE_LAT *
# $COS2[$lat + $lat2]; # optimization would provide almost no efficiency advantage
($COS[$rounded_scaled_abs_mean_lat] // ($COS[$rounded_scaled_abs_mean_lat] = cos(deg2rad($mean_lat))));
# my $diff_lon = ($lon * cos(deg2rad($lat)) - $prev_lon * cos(deg2rad($prev_lat))) * METERS_PER_DEGREE_LAT;
return $diff_lat * $diff_lat + $diff_lon * $diff_lon;
}
my @SQR;
sub sqrt_with_cache {
my $sq_dis = $_[0];
# with the following, cache hit rate is around 98% and resulting error is rarely more than a meter:
return sqrt($sq_dis) if $sq_dis >= 10000; # do not cache for distances >= 100 m
my $rounded_sq_dis = $sq_dis + 0.5;
return $SQR[$rounded_sq_dis] // ($SQR[$rounded_sq_dis] = sqrt($sq_dis));
}
sub distance_3d {
my ($sq_dis2d, $ele, $ele2) = @_;
my $diff_ele = diff_nonempty($ele, $ele2) // 0; # assuming no altitude change if no altitude available
return sqrt_with_cache($sq_dis2d + $diff_ele * $diff_ele);
}
sub distance {
my ($lat, $lon, $ele, $lat2, $lon2, $ele2) = @_;
stacktrace()
if !defined $lat || !defined $lon || !defined $ele
|| !defined $lat2 || !defined $lon2 || !defined $ele2;
return distance_3d(sq_distance_2d($lat, $lon, $lat2, $lon2), $ele, $ele2);
#
#$distance = Math::Trig::great_circle_distance( #does not account for $diff_ele!
# deg2rad($lon) , deg2rad(90 - $lat ),
# deg2rad($lon2), deg2rad(90 - $lat2),
# 40*1000*1000/pi/2); #http://perldoc.perl.org/Math/Trig.html
## debug "diff_lat=$diff_lat, diff_lon=$diff_lon, dis=$dis, distance=$distance";
}
sub comp_diffs {
my $i = shift; # calculate differences relative to previous point PREV($i)
# $prev_comp_spd is assumed to be average speed computed between previous points
my $prev_i = PREV($i);
my ($prev_ele, $prev_sec, $prev_dis, $prev_comp_spd) = ($ELE[$prev_i], $SEC[$prev_i], $DIS[$prev_i], $SPD[$prev_i]);
my ( $ele, $sec, $dis, $spd) = ($ELE[ $i], $SEC[ $i], $DIS[ $i], $SPD[ $i]);
my $diff_ele = diff_nonempty($ele, $prev_ele);
#http://forums.howwhatwhy.com/showflat.php?Cat=&Board=scigen&Number=-208125
my $timediff = diff_defined($sec, $prev_sec);
my $rate= rate($diff_ele, $timediff);
my $comp_spd = defined $timediff ? ($timediff > 0 ? $dis / $timediff : $prev_comp_spd) : "";
$spd_prec_len = max($spd_prec_len, length(spd_str($comp_spd))) if $comp_spd ne ""; # used only for spd_string
my $acc = $comp_spd ne "" && $prev_comp_spd ne "" && $timediff ? ($comp_spd - $prev_comp_spd) / $timediff : "";
return ($diff_ele // "", $timediff // "", $rate, $dis, $comp_spd, $acc);
}
my @SLO; # cached slope; no need to use quick approximation (such as quotient of elevation difference and 3d distance)
sub slope {
my ($prev_i, $i) = @_; # both are assumed to be defined
my $value = $SLO[$i];
debug_log "$i $TIM[$i] slope=$value (cached)" if defined $value;
return $value if defined $value;
return undef if $ELE[$i] eq "" || $ELE[$prev_i] eq "";
my $ele_diff = $ELE[$i] - $ELE[$prev_i];
my $sq_dis_2d = $DIS2[$i]; # not taking into account: $ele_avg = ($ELE[$i] + $ELE[$prev_i]) / 2
$value = $ele_diff == 0 ? 0
: $sq_dis_2d == 0 ? ($ele_diff < 0 ? -90 : 90)
: atan2($ele_diff, sqrt_with_cache($sq_dis_2d)) * RAD2DEG;
debug_log "$i $TIM[$i] slope=$value";
return ($SLO[$i] = $value);
}
use constant N_AVG_SLOPE => 4;
sub avg_slope { # between the last N_AVG_SLOPE points, assuming 0 where not available
my $sum = 0;
my $i = $_[0];
my $prev_i = PREV($i);
my $n;
for ($n = 0; $n < N_AVG_SLOPE; $n++) {
last if $SEG[$i] || section($i);
my $slope = slope($prev_i, $i) // 0;
$sum += $slope;
($i, $prev_i) = ($prev_i, PREV($prev_i));
}
# if ($n == 1) { # use as fallback the average with slope of next point, if available
# my $i2 = NEXT($_[0]);
# my $slope2 = defined $i2 ? slope($i2) : undef;
# return ($sum + $slope2) / 2 if defined $slope2;
# }
debug_log "$_[0] $TIM[$_[0]] avg_slope=".($n == 0 ? "undef" : $sum / N_AVG_SLOPE);
return $n == 0 ? undef : $sum / N_AVG_SLOPE
}
sub get_direction { # compute and store in @DIR the direction from PREV($i) to $i, and return it
my $i = $_[0];
return $DIR[$i] if defined $DIR[$i]; # return cached value
my $prev_i = PREV($i);
return undef unless defined $prev_i;
my $curr_lat_diff = $LAT[$i] - $LAT[$prev_i];
my $curr_lon_diff = $LON[$i] - $LON[$prev_i];
return undef unless $curr_lat_diff || $curr_lon_diff;
return $DIR[$i] = atan2($curr_lon_diff, $curr_lat_diff);
}
sub comp_angle { # calculate horizontal direction change (i.e., turning angle)
# between last, current, and next point, or undef if not available
# provides almost no efficiency penalty
my ($i, $timediff, $dis) = @_;
my ($theta_diff, $spd2) = (undef, "");
my $next_i = NEXT($i);
if (defined $next_i && !$SEG[$next_i] && !section($i) && !section($next_i)) { # next point exists and is not at segment start and not at merge start/pause
my $next_dis = $DIS[$next_i];
my $next_timediff = diff_defined($SEC[$next_i], $SEC[$i]);
my $timediff2 = $timediff eq "" || !defined $next_timediff ? 0 : $timediff + $next_timediff;
my $dis2 = $dis eq "" || $next_dis eq "" ? 0 : $dis + $next_dis;
$spd2 = $timediff2 <= 0 || $dis2 <= 0 ? "" : $dis2 / $timediff2; # average speed
if ($spd2 ne "" && MPS2KMPH * $spd2 > MAX_PLAUSIBLE_ANGLE_SPD_THRESHOLD) {
my ($theta1, $theta2) = (get_direction($i), get_direction($next_i));
if (defined $theta1 && defined $theta2) {
# debug (($theta1 * RAD2DEG)." <$i> ".($theta2* RAD2DEG));
$theta_diff = ($theta2 - $theta1) * RAD2DEG % 360;
$theta_diff -= 360 if $theta_diff >= 180;
}
}
}
return ($theta_diff, $spd2);
}
### parse command line
# TODO clean up use of ARGV
for (my $i = 0; $#ARGV - $i >= 0; ) {
my $opt = $ARGV[$i];
my $arg1 = $ARGV[$i + 1];
my $arg2 = $ARGV[$i + 2];
# not checking for duplicate options
if ($opt eq "-h" || $opt =~ /^-*help$/) {
print_line($usage);
exit 0;
} elsif ($opt eq "-version") {
print_line($TOOL_ID);
exit 0;
} elsif ($opt eq "-swim" ||
$opt eq "-walk" ||
$opt eq "-cycle" ||
$opt eq "-drive" ||
$opt eq "-fly") {
$activity = $opt;
} elsif ($opt eq "-no_sanitize") {
$sanitize = !SANITIZE_TRKPTS;
} elsif ($opt eq "-no_insert") {
$insert_points = 0;
} elsif ($opt eq "-smooth") {
$smoothing = 1;
} elsif ($opt eq "-phases") {
$phases = 1;
} elsif ($opt eq "-merge") {
abort("missing file argument for -$opt option") if $#ARGV - $i < 1;
$merge = $arg1;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-segs" || $opt eq "-days") {
if ($opt eq "-segs") {
abort("cannot use both -days and -$opt option") if $days;
$segs = 1;
} else {
abort("cannot use both -segs and -$opt option") if $segs;
$days = 1;
}
if ($#ARGV - $i >= 1 && $arg1 =~ m/^\d/) {
abort("argument '$arg1' of -$opt option is not of the form <n>..[<m>][(+|-)<d>] with natural numbers n, m, and integer d")
unless $arg1 =~ m/^(\d+)\.\.(\d+)?([-+]\d+)?+$/ && $1 > 0;
($part_start, $part_end, $part_offset) = ($1, $2, $3); # $part_end < $part_start will lead to empty selection, just like without $opt
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
}
} elsif ($opt eq "-tz") {
abort("missing value argument for -$opt option") if $#ARGV - $i < 1;
abort("cannot parse value argument in '$opt $arg1'") unless looks_like_number($arg1);
$tz = $arg1 + 0;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-split") {
abort("missing base file name argument for -$opt option") if $#ARGV - $i < 1;
$split = $arg1;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-lean_stat_wpts") {
$lean_stat_wpts = 1;
} elsif ($opt eq "-info_wpts") {
$info_wpts = 1;
} elsif ($opt eq "-warn_wpts") {
$warn_wpts = 1;
} elsif ($opt eq "-cmt_wpts") {
abort("missing pattern argument for -$opt option") if $#ARGV - $i < 1;
$cmt_wpts = $arg1;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-src_wpts") {
abort("missing pattern argument for -$opt option") if $#ARGV - $i < 1;
$src_wpts = $arg1;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-weight") {
abort("missing value argument for -$opt option") if $#ARGV - $i < 1;
abort("cannot parse value argument in '$opt $arg1'") unless looks_like_number($arg1);
$weight = $arg1 + 0;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-begin" || $opt eq "-end") {
abort("missing time argument for $opt option") if $#ARGV - $i < 1;
my $sec = str_to_epoch($arg1);
abort("cannot parse time argument in '$opt $arg1'") unless defined $sec;
$begin_sec = $sec if $opt eq "-begin";
$end_sec = $sec if $opt eq "-end";
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-resolution") {
abort("missing number of seconds argument for $opt option") if $#ARGV - $i < 1;
abort("illegal natural number argument in '$opt $arg1'") unless $arg1 =~ m/^\d+$/;
$min_input_timediff = $arg1 + 0;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-max" || $opt eq "-min") {
abort("missing element name argument for $opt option") if $#ARGV - $i < 1;
abort("missing limit argument for -$opt option") if $#ARGV - $i < 2;
abort("cannot parse limit argument in '$opt $arg1 $arg2'") unless looks_like_number($arg2);
($max_elem, $max_elem_limit) = ($arg1, $arg2 + 0) if $opt eq "-max";;
($min_elem, $min_elem_limit) = ($arg1, $arg2 + 0) if $opt eq "-min";;
splice @ARGV, $i + 1, 2; # remove from ARGV the option arguments
} elsif ($opt eq "-max_ext" || $opt eq "-min_ext") {
abort("missing extension name argument for $opt option") if $#ARGV - $i < 1;
abort("missing limit argument for -$opt option") if $#ARGV - $i < 2;
abort("cannt parse limit argument in '$opt $arg1 $arg2'") unless looks_like_number($arg2);
($max_ext, $max_ext_limit) = ($arg1, $arg2 + 0) if $opt eq "-max_ext";
($min_ext, $min_ext_limit) = ($arg1, $arg2 + 0) if $opt eq "-min_ext";
splice @ARGV, $i + 1, 2; # remove from ARGV the option arguments
} elsif ($opt eq "-min_dist") {
abort("missing distance argument for -$opt option") if $#ARGV - $i < 1;
$min_dist = $arg1;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-min_angle") {
abort("missing angle argument for -$opt option") if $#ARGV - $i < 1;
$min_angle = $arg1;
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-prune_wpts") {
$prune_wpts = 1;
} elsif ($opt eq "-prune_cmts") {
$prune_cmts = 1;
} elsif ($opt eq "-prune_exts") {
$prune_exts = 1;
} elsif ($opt eq "-ni") {
$output_info = 0;
} elsif ($opt eq "-nw") {
$output_warnings = 0;
} elsif ($opt eq "-o") {
# not checking for operlap with shell-level redirection of STDOUT using '>'
abort("missing outfile argument for -o option") if $#ARGV - $i < 1;
open($out, "> $arg1") || abort("FATAL: cannot open output file $arg1: $.");
splice @ARGV, $i + 1, 1; # remove from ARGV the option argument
} elsif ($opt eq "-debug") {
$debug = 1;
} elsif ($opt =~ m/^-/) {
abort("unknown option: $opt");
} else {
$i++;
next; # infile
}
splice @ARGV, $i, 1; # remove from ARGV the option just handled
}
if ($prune_exts) {
warning("-min_ext option has little effect since -prune_exts is given") if $min_ext;
warning("-max_ext option has little effect since -prune_exts is given") if $max_ext;
}
abort "cannot smoothen tracks without sanitizing" if $smoothing && !$sanitize; # TODO maybe fix this limitation
$part_start = 1 unless defined $part_start;
$part_offset = 0 unless defined $part_offset;