-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpxconv
executable file
·2356 lines (2143 loc) · 112 KB
/
gpxconv
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 typically produced by GPS loggers.
#
# Reads from file(s) given as argument (or STDIN) and writes to STDOUT or a file.
# Can append segments from multiple tracks and files (sequential composition), using the metadata of the first track.
# Can complete gaps in input file(s) by merging data from an alternative GPX file (parallel composition).
# Concatenates all given tracks (or routes) preserving segments, collecting waypoints.
# The metadata (header) of the first input track is used for the output track.
# Reports missing data and by default sanitizes points containing implausible data.
# Optionally filters out points before or after given time limits.
# Optionally filters out points with an element value below or above given limits.
# 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.
# Optionally inserts interpolated points in long gaps (default 1800 seconds sufficient for exiftool).
# Optionally corrects elevation and smoothens tracks.
# (Orthometric height = GPS ellipsoidal height - geoid height,
# see http://www.unavco.org/edu_outreach/tutorial/geoidcorr.html)
# Produces statistics including ascent/descent rates, optionally also for climbing phases.
# Optionally produces additional statistics on a per-segment or per-day basis.
# Optionally calculates approx. total energy spent by biking along the resulting track.
# Prints information (if enabled), any warnings (if enabled), and errors to STDERR.
#
use constant TOOL_NAME => "GPXConv";
use constant TOOL_VERSION => "2.8.2";
my $TOOL_ID = TOOL_NAME." v".TOOL_VERSION;
my $usage =
"Usage: gpxconv <option(s) and infile(s)> [> <outfile>]
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
-smooth - smoothen tracks
-phases - analyze and provide statistics for ascent/descent phases
-segs <n>..[<m>][(+|-)<d>] - add statistics per segment n..m, adapt their numbers +/-d
-days <n>..[<m>][(+|-)<d>] - add statistics per day n..m, may adapt their numbers +/-d
-merge <file> - complete gaps in infile(s) by data from given GPX 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
-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
-prune_wpts - remove waypoints
-prune_cmts - remove comments
-prune_exts - remove extensions
-nw - do not print warnings
-ni - do not print information
-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-2024 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\[\d*\]\]></name>
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
# smoothing control
use constant MERGE_FILL_GAP => 60; # minimum gap duration in seconds to be filled by merging
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
use constant INSERT_POINTS => 1; # 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)
# warning output control
use constant PRINT_WARNINGS => 1; # whether printing warnings is enabled by default
use constant PRINT_INFO => 1; # whether printing information is enabled by default
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 => 2; # threshold for speed measuring deviation warning (in km/h)
# 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 MAX_PLAUSIBLE_ANGLE_DIFF => 170; # maximal plausible turning angle above speed threshold
use constant MAX_PLAUSIBLE_ANGLE_SPD_THRESHOLD => 2; # speed threshold for maximal plausible turning angle: 7.2 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 => 10000 * 1000 / 90; # on Earth, by definition
use constant LAT_PRECISION => "%.5f"; # latitude resolution = 0.00001° (<= 1.11 meters)
use constant LON_PRECISION => "%.5f"; # longitude resolution = 0.00001° (<= 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 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
# trkpt flags
use constant DUPLICATED_POINT => 1 << 0;
use constant INSERTED_POINT => 1 << 1;
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;
# global option variables
my $debug = 0;
my $merge;
my $num_ignored_hdrs = 0;
my $begin_sec;
my $num_ignored_before = 0;
my $end_sec;
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 $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;
my $print_warnings = PRINT_WARNINGS;
my $print_info = PRINT_INFO;
# trackpoint data
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 @DIS; # derived from LAT and LON, and ELE if available, also from point before, 0 for first point
my @RAT; # derived from optionally ELE and SEC, also from point before, or "" if not available
my @SPD; # as recorded or computed (as average since previous point if FLG contains COMPUTED_SPEED), or "" if not available
my @CMT; # 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
# 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_INDEX;
my @PHASE_END_INDEX;
my $ascent__phases_suppressed = 0;
my $descent_phases_suppressed = 0;
# global state variables
my $HEAD;
my $found_corr = 0;
my $lat, my $lon, my $ele, my $tim, my $sec, my $spd; # TODO make local
my $prev_lat, my $prev_lon, my $prev_ele, my $prev_tim, my $prev_sec, my $prev_comp_spd, my $prev_rate, my $prev_acc; # TODO make local
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 ($segs, $days);
my ($part, $part_start, $part_end, $part_offset);
# in the following arrays, index ($part_start - 1) will be used for the overall values
my (@MAX_SPD , @MIN_ELE , @MAX_ELE , @MAX_GAIN , @MAX_LOSS ); # TODO remove these redundant arrays (GAIN/LOSS via RAT)
my (@MAX_SPD_INDEX, @MIN_ELE_INDEX, @MAX_ELE_INDEX, @MAX_GAIN_INDEX, @MAX_LOSS_INDEX);
my (@LAST_GAIN_INDEX, @LAST_LOSS_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) = (0, 0);
my $avg_timediff;
# for calculating relative deviation between recorded and computed speed
my $sum_speed = 0;
my $sum_speed_deviation = 0;
my $sum_timediff_mov = 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 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 $print_warnings;
}
sub info {
print_line("INFO : $_[0]") if $print_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 stacktras, may use: perl -d:Confess
sub stacktrace {
use Devel::StackTrace;
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];
my $s = $_[0];
return undef unless $s =~ m/^\d\d\d\d-\d\d-\d\dT\d\d(:\d\d(:\d\d(\.\d{1,})?)?)?Z$/; # 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 $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,
$millisec == 0 ? "" : substr(substr($millisec, 1)."00", 0, 4)
);
}
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 {
stacktrace() if !defined $_[1] || $_[1] eq "";
my $len = $_[0];
my $ele = $_[1];
$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 { return "point $_[0] ".($tim ne "" ? "tim=$tim" : "$lat , $lon ".($ele eq "" ? "none" : $ele)); }
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;
}
my $lat_prec_len = my $lat_full_len =
my $lon_prec_len = my $lon_full_len =
my $ele_prec_len = my $ele_full_len = my $tim_len = 1; # used only for formatting
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;
}
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); # may be 0
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 && $str =~ s#[ \t]*(<cmt>.*?</cmt>)\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;
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 { info_trkpt_i( -1, $_[0], $_[1] ); }
sub warn_trkpt { warn_trkpt_i( -1, $_[0], $_[1] ); }
sub print_trkpt { print_trkpt_i( -1, $_[0], $_[1] ); }
sub info_trkpt_i {
print_trkpt_i( $_[0], "INFO : $_[1]", $_[2] ) if $print_info;
}
sub warn_trkpt_i {
print_trkpt_i( $_[0], "WARNING: $_[1]", $_[2] ) if $print_warnings;
}
sub print_trkpt_i {
my $i = $_[0];
my $head = $_[1]; # may be empty
my $tail = $_[2]; # may be empty
my ( $lati, $long, $elev, $t ) =
$i < 0
? ( $lat, $lon, $ele, $tim )
: ( $LAT[$i], $LON[$i], $ELE[$i], $TIM[$i] );
# using original precision here for better traceability
# $lati = lat_str($lati);
# $long = lon_str($long);
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 = $t eq "NO" ? "" : " <time>".($t eq "" ? "NONE" : $t);
print_line("$head "
. "<trkpt"
. ' lat="' . ( $lati . '"' . ( ' ' x max( 0, $lat_full_len - length($lati) ) ) )
. ' lon="' . ( $long . '"' . ( ' ' x max( 0, $lon_full_len - length($long) ) ) )
. " <ele>" . ele_string(-$ele_full_len, $elev)
. $time . ($tail ? " " x max(0, $tim_len + length(" <time>") - length($time)) : "")
. $tail);
abort("") if ( $head =~ "^FATAL:" );
}
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 rate { return defined $_[0] && $_[1] ? H2S * $_[0] / $_[1] : ""; } # ascent/descent rate in m/h
sub recalculate_DIS { my $i = $_[0];
return if $i <= 0 || $SEG[$i];
$DIS[$i] = distance($LAT[$i ], $LON[$i ], $ELE[$i ],
$LAT[$i - 1], $LON[$i - 1], $ELE[$i - 1]);
}
sub recalculate_SPD { my $i = $_[0];
return if $i <= 0 || $SEG[$i] || !($FLG[$i] & COMPUTED_SPEED);
my $diff_time = diff_defined($SEC[$i], $SEC[$i - 1]);
$SPD[$i] = $DIS[$i] / $diff_time if $diff_time;
}
sub recalculate_RAT { my $i = $_[0];
return if $i <= 0 || $SEG[$i];
$RAT[$i] = rate(diff_nonempty($ELE[$i], $ELE[$i - 1]), diff_defined($SEC[$i], $SEC[$i - 1]));
}
sub recalculate_all {
my $i = $_[0];
recalculate_DIS($i);
recalculate_SPD($i);
recalculate_RAT($i);
}
sub remove_trkpt { my ($i, $last, $undo_gap_fill) = @_;
# undo_gap_fill means not counting the point being ignored, must ignore segment start and can re-calculate the distance simply by addition due to linear interpolation
$IGN[ $i + 1 ] += $IGN[$i] + ($undo_gap_fill ? 0 : 1); # indicate that previous point has been ignored, in addition to any previous ignores
$SEG[ $i + 1 ] = 1 if $i < $last && $SEG[$i] && !$undo_gap_fill; # copy over any segment start
my $dis_before = $DIS[$i];
splice @IGN, $i, 1;
splice @SEG, $i, 1;
splice @FLG, $i, 1;
splice @LAT, $i, 1;
splice @LON, $i, 1;
splice @ELE, $i, 1;
splice @TIM, $i, 1;
splice @SEC, $i, 1;
splice @DIS, $i, 1;
splice @RAT, $i, 1;
splice @SPD, $i, 1;
splice @CMT, $i, 1;
splice @SRC, $i, 1;
splice @FIX, $i, 1;
splice @EXT, $i, 1;
if ($i <= $last) {
if ($undo_gap_fill) {
$DIS[$i] += $dis_before if $i > 0;
} else {
recalculate_DIS($i);
recalculate_SPD($i);
}
recalculate_RAT($i);
}
}
sub distance {
stacktrace() if !defined $_[0] || !defined $_[1] || !defined $_[2] || !defined $_[3] || !defined $_[4] || !defined $_[5];
my $lat = $_[0];
my $lon = $_[1];
my $ele = $_[2];
my $prev_lat = $_[3];
my $prev_lon = $_[4];
my $prev_ele = $_[5];
my $diff_lat = ( $lat - $prev_lat ) * METERS_PER_DEGREE_LAT;
my $diff_lon = ( $lon - $prev_lon ) * METERS_PER_DEGREE_LAT *
cos( deg2rad( ( $lat + $prev_lat ) / 2 ) );
#my$diff_lon = ($lon * cos(deg2rad($lat)) - $prev_lon * cos(deg2rad($prev_lat))) * METERS_PER_DEGREE_LAT;
my $diff_ele = diff_nonempty($ele, $prev_ele) // 0;
# assuming no altitude change if no altitude available
return sqrt( $diff_lat * $diff_lat + $diff_lon * $diff_lon + $diff_ele * $diff_ele );
#$distance = Math::Trig::great_circle_distance( #does not account for $diff_ele!
# deg2rad($lon) , deg2rad(90 - $lat ),
# deg2rad($prev_lon), deg2rad(90 - $prev_lat),
# 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 distance_curr { # of $lat, $lon, $ele
return distance( $lat, $lon, $ele, $_[0], $_[1], $_[2] );
}
sub comp_diffs()
{ # of $lat, $lon, $ele relative to $prev_lat, $prev_lon, $prev_ele, so speed is relative to previous point
# $prev_comp_spd is assumed to be average speed computed between previous points
# recalculation of distance and elevation difference since coordinates may have been smoothened # TODO recalculate DIS on smoothing
my $dis = distance_curr( $prev_lat, $prev_lon, $prev_ele );
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 );
}
### 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 "-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") {
abort("missing argument for -$opt option") if $#ARGV - $i < 1;
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;
if ($opt eq "-segs") {
abort("cannot use both -days and -$opt option") if $days;
$segs = $arg1;
} else {
abort("cannot use both -segs and -$opt option") if $segs;
$days = $arg1;
}
($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 "-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 "-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 "-prune_wpts" ) {
$prune_wpts = 1;
}
elsif ( $opt eq "-prune_cmts" ) {
$prune_cmts = 1;
}
elsif ( $opt eq "-prune_exts" ) {
$prune_exts = 1;
}
elsif ( $opt eq "-nw" ) {
$print_warnings = 0;
}
elsif ( $opt eq "-ni" ) {
$print_info = 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" );
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;
}
if ( $activity eq "-swim" ) {
$MIN_TIMEDIFF = 4;
$MAX_PLAUSIBLE_SPEED = 7;
$MAX_PLAUSIBLE_ACCEL = 1;
$MAX_PLAUSIBLE_DECEL = 2;
$MAX_PLAUSIBLE_ELE_GAIN = 1;
$MAX_PLAUSIBLE_ELE_LOSS = 1;
}
elsif ( $activity eq "-walk" ) {
$MIN_TIMEDIFF = 4;
$MAX_PLAUSIBLE_SPEED = 20;
$MAX_PLAUSIBLE_ACCEL = 0.5;
$MAX_PLAUSIBLE_DECEL = 1;
$MAX_PLAUSIBLE_ELE_GAIN = 1800;
$MAX_PLAUSIBLE_ELE_LOSS = 3600;
}
elsif ( $activity eq "-cycle" ) {
$MIN_TIMEDIFF = 2;
$MAX_PLAUSIBLE_SPEED = 80;
$MAX_PLAUSIBLE_ACCEL = 4;
$MAX_PLAUSIBLE_DECEL = 8;
$MAX_PLAUSIBLE_ELE_GAIN = 3000;
$MAX_PLAUSIBLE_ELE_LOSS = 9000;
}
elsif ( $activity eq "-drive" ) { # default
$MIN_TIMEDIFF = 2; # in seconds
$MAX_PLAUSIBLE_SPEED = 200; # maximal speed in km/h
$MAX_PLAUSIBLE_ACCEL = 5; # maximal acceleration m/s/s
$MAX_PLAUSIBLE_DECEL = 10; # maximal deceleration m/s/s
$MAX_PLAUSIBLE_ELE_GAIN = 20000; # maximal ascent rate in m/h
$MAX_PLAUSIBLE_ELE_LOSS = 20000; # maximal descent rate in m/h
$PHASES_REPORT_THRESHOLD = 100;
}
elsif ( $activity eq "-fly" ) {
$MIN_TIMEDIFF = 1;
$MAX_PLAUSIBLE_SPEED = 1200;
$MAX_PLAUSIBLE_ACCEL = 10;
$MAX_PLAUSIBLE_DECEL = 10;
$MAX_PLAUSIBLE_ELE_GAIN = 30000;
$MAX_PLAUSIBLE_ELE_LOSS = 50000;
$PHASES_REPORT_THRESHOLD = 100;
} else {
abort("unknown activity: $activity\naborting");
}
my $INSERTION_MAX_SPEED = $MAX_PLAUSIBLE_SPEED / 2;
### main loops
## read all trackpoints from all track segments, optionally completing them
{ # TODO re-format
my $ele_miss_start = 0; # first index of recent stretch with missing ele ; TODO restrict scope
my $tim_miss_start = 0; # first index of recent stretch with missing time; TODO restrict scope
my $num_no_ele = 0;
my $ele_gap_length = 0;
my $num_no_time = 0;
my $time_gap_length = 0;
my $prev_tim = "";
my $prev_sec;
# $prev_avail_tim = "";
$/ = "<trkpt ";
if ($merge) {
open M, $merge || abort("FATAL: cannot open alternative GPX source file $merge: $.") if $#TIM < 0;
<M>; # first item is before "<trktpt"
}
my ($lat1, $lon1, $ele1, $tim1, $sec1, $spd1, $cmt1, $src1, $fix1, $exts1) if $merge; # current end of gap to be merged
my ($lat2, $lon2, $ele2, $tim2, $sec2, $spd2, $cmt2, $src2, $fix2, $exts2) if $merge; # current trkpt from alternative input
sub next_trkpt2() {
my $trkpt2;
my $ignore2 = 1;
while ($ignore2 && defined($trkpt2 = <M>)) {
$trkpt2 =~ m#(.*?</trkpt>)#s;
$trkpt2 = $1;
abort("FATAL: cannot find end of trackpoint: <trkpt $_") unless $trkpt2;
($lat2, $lon2, $ele2, $tim2, $sec2, $spd2, my $rest_unused2, $cmt2, $src2, $fix2, $exts2, $ignore2) = parse_point("<trkpt $trkpt2") if $trkpt2;
}
## debug_log "read non-ignored point from alt input with lat=$lat2 lon=$lon2 ele=$ele2 tim=$tim2 sec=".($sec2 // "none")." spd=".spd_or_none($spd2) if $trkpt2;
return $trkpt2;
}
my $in_merge = 0; # if set, using trkpt from $merge
if ($merge && !next_trkpt2()) {
abort("FATAL: no trkpt found in alternative input $merge");
$merge = 0;
close M;
}
# TODO before further complicating input handling, split file reading and parsing from any further processing
for (my $state = 0,
my $prev_avail_sec, my $prev_avail_ele = "", my $ele_miss_length = 0, my $tim_miss_length = 0,
my $i = 0;
$in_merge ? (next_trkpt2() ? 1 : ($in_merge = -$in_merge, $in_merge != -2 && defined($_ = <>))) # EOF in $merge
: (defined($_ = <>) ||
# in case EOF in infile(s):
($merge && (info("infile(s) ended before alternative input"), 1) ? ($in_merge = 2, 1) : 0));
) {
# anywhere (in headers, tracks, waypoints, trackpoints, ...):
$num_pruned_cmts += s#[ \t]*<cmts>.*?</cmt>\n?##sg if $prune_cmts;
$num_pruned_descs += s#[ \t]*<desc>.+?</desc>\n?##sg if PRUNE_DESCS;
$num_pruned_links += s#[ \t]*<link.*?>.+?</link>\n?##sg if PRUNE_LINKS;
$num_pruned_exts += s#[ \t]*<extensions>.*?</extensions>\n?##sg if $prune_exts;
if (!$prune_exts && ($min_ext || $max_ext)) {
s@(<extensions>)(.*?)(</extensions>\n?)@ my ($start, $ext, $end) = ($1, $2, $3);
$ext =~ s#(<$min_ext>\s*(-?[\.\d]+)\s*</$min_ext>)#$2 < $min_ext_limit ? ($num_ext_below++, "") : $1#esg if $min_ext;
$ext =~ s#(<$max_ext>\s*(-?[\.\d]+)\s*</$max_ext>)#$2 > $max_ext_limit ? ($num_ext_above++, "") : $1#esg if $max_ext;
$ext eq "" ? "" : "$start$ext$end"
@esg;
}
#collect waypoints, possibly in later infile(s) headers
my $prev_wpt_time_stripped = "";
while (!$in_merge && s#(<wpt .+?)(</wpt>)\n?##s)
{
my $wpt = $1 . $2;
# workaround for OruxMaps partly duplicating waypoints of <type>Finishing Point</type> when manually starting new segment
my $wpt_time_stripped = $wpt;
$wpt_time_stripped =~ s#<time>.*</time>##;
next if $wpt =~ m#<type>Finishing Point</type># && $wpt_time_stripped eq $prev_wpt_time_stripped;
$prev_wpt_time_stripped = $wpt_time_stripped;
($lat, $lon, $ele, $tim, my $sec, my $spd_unused, my $rest, my $cmt_unused, my $src_unused, my $fix_unused, my $exts, my $ignore) = parse_point($wpt); # collect some basic data even if pruned
$rest =~ s#^<wpt[^>]*>##; # ignoring any further wpt attributes, yet there should not be any (besides lat and lon)
$rest =~ s#</wpt>$##;
++$num_pruned_wpts if $prune_wpts && !$ignore;
if (!$ignore && !$prune_wpts
&& !( PRUNE_AUTOMATIC_WPTS &&
$rest =~ m#<name><!\[CDATA\[\d*\]\]></name># && ++$num_auto_wpts )
# better not leave out waypoints added previously by this tool because this would disturb the ordering and duplicates are now taken care of by add_stat_point():
# && !( $rest =~ m#\[(start|end.*?)\]# ) # start/end waypoint added previously by this tool
# && # waypoint with statistics added previously by this tool:
# !($rest =~ m#\[((max|min)\s+(altitude|elevation|height)|max\s+speed|max\s+(climb|ascent|descent)\s+rate|total\s+(ascent|descent|gain|loss))\s+=\s+[+-]?[\.\d]+ k?m(\/h)?( at -?[\.\d]+ km/h|;\s+avg\s+rate\s+=\s+[+-]?[\d.]+ m/h)?\]#)
)
{
push @WLAT, $lat;
push @WLON, $lon;
push @WELE, $ele;
push @WTIM, $tim;
push @WSEC, $sec;
push @WTXT, $rest . $exts;
$wpt =~ s/(^|\n)/\n /sg; # indent waypoint lines, just for better readability of diagnostics
push @WSTR, "'$wpt\n'";
}
}
sub warn_smmoothing { warning("smoothing has already been done on input") if $_[0] =~ m#(\d+) points .*?smoothened($|\W)# && $1 > 0; }
if ( $state == 0 ) {
# processing first header (of first input file)
if (s#\r?\nGPXConv statistics (.*?)GPXConv statistics end\r?\n##s) # remove any earlier statistics section
{
warn_smmoothing($1) if $smoothing;
}
if (m#$/#s) {
s#$/##s; #remove trailing "<trkpt "
}
else {
s#(^.*</type>).*#$1\n<trkseg>\n#s; #ignore rest of (header-only) file having no trkpt
}
s#[ \t]+(\r?\n)$#$1#s; #remove any trailing spaces on line before
s#[ \t]*(<trkseg>)#$1#s;
$HEAD = $_;
$state = 1; # expecting the very first trkpt
}
elsif (!$in_merge && m#(<gpx[ >])#s) { # processing further GPX header, typically from next file
++$num_ignored_hdrs;
if ($smoothing && m#\r?\nGPXConv statistics (.*?smoothened)(.*?)GPXConv statistics end\r?\n#)
{
warn_smmooting($1);
}
if ( $#TIM >= 0 ) { # typically, new file
info_trkpt_i( $i - 1, "end of segment at", "" ) if $i > 0;
info("further track, from file $ARGV");