]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/Track.java
Version 10, May 2010
[GpsPrune.git] / tim / prune / data / Track.java
1 package tim.prune.data;
2
3 import java.util.List;
4
5 import tim.prune.UpdateMessageBroker;
6 import tim.prune.config.Config;
7 import tim.prune.function.edit.FieldEdit;
8 import tim.prune.function.edit.FieldEditList;
9 import tim.prune.gui.map.MapUtils;
10
11
12 /**
13  * Class to hold all track information,
14  * including track points and waypoints
15  */
16 public class Track
17 {
18         // Data points
19         private DataPoint[] _dataPoints = null;
20         // Scaled x, y values
21         private double[] _xValues = null;
22         private double[] _yValues = null;
23         private boolean _scaled = false;
24         private int _numPoints = 0;
25         private boolean _hasTrackpoint = false;
26         private boolean _hasWaypoint = false;
27         // Master field list
28         private FieldList _masterFieldList = null;
29         // variable ranges
30         private AltitudeRange _altitudeRange = null;
31         private DoubleRange _latRange = null, _longRange = null;
32         private DoubleRange _xRange = null, _yRange = null;
33
34
35         /**
36          * Constructor for empty track
37          */
38         public Track()
39         {
40                 // create field list
41                 _masterFieldList = new FieldList(null);
42                 // make empty DataPoint array
43                 _dataPoints = new DataPoint[0];
44                 _numPoints = 0;
45                 // needs to be scaled
46                 _scaled = false;
47         }
48
49
50         /**
51          * Load method, for initialising and reinitialising data
52          * @param inFieldArray array of Field objects describing fields
53          * @param inPointArray 2d object array containing data
54          * @param inAltFormat altitude format
55          */
56         public void load(Field[] inFieldArray, Object[][] inPointArray, Altitude.Format inAltFormat)
57         {
58                 if (inFieldArray == null || inPointArray == null)
59                 {
60                         _numPoints = 0;
61                         return;
62                 }
63                 // copy field list
64                 _masterFieldList = new FieldList(inFieldArray);
65                 // make DataPoint object from each point in inPointList
66                 _dataPoints = new DataPoint[inPointArray.length];
67                 String[] dataArray = null;
68                 int pointIndex = 0;
69                 for (int p=0; p < inPointArray.length; p++)
70                 {
71                         dataArray = (String[]) inPointArray[p];
72                         // Convert to DataPoint objects
73                         DataPoint point = new DataPoint(dataArray, _masterFieldList, inAltFormat);
74                         if (point.isValid())
75                         {
76                                 _dataPoints[pointIndex] = point;
77                                 pointIndex++;
78                         }
79                 }
80                 _numPoints = pointIndex;
81                 // Set first track point to be start of segment
82                 DataPoint firstTrackPoint = getNextTrackPoint(0);
83                 if (firstTrackPoint != null) {
84                         firstTrackPoint.setSegmentStart(true);
85                 }
86                 // needs to be scaled
87                 _scaled = false;
88         }
89
90
91         /**
92          * Load the track by transferring the contents from a loaded Track object
93          * @param inOther Track object containing loaded data
94          */
95         public void load(Track inOther)
96         {
97                 _numPoints = inOther._numPoints;
98                 _masterFieldList = inOther._masterFieldList;
99                 _dataPoints = inOther._dataPoints;
100                 // needs to be scaled
101                 _scaled = false;
102         }
103
104         /**
105          * Request that a rescale be done to recalculate derived values
106          */
107         public void requestRescale()
108         {
109                 _scaled = false;
110         }
111
112         /**
113          * Extend the track's field list with the given additional fields
114          * @param inFieldList list of fields to be added
115          */
116         public void extendFieldList(FieldList inFieldList)
117         {
118                 _masterFieldList = _masterFieldList.merge(inFieldList);
119         }
120
121         ////////////////// Modification methods //////////////////////
122
123
124         /**
125          * Combine this Track with new data
126          * @param inOtherTrack other track to combine
127          */
128         public void combine(Track inOtherTrack)
129         {
130                 // merge field list
131                 _masterFieldList = _masterFieldList.merge(inOtherTrack._masterFieldList);
132                 // expand data array and add other track's data points
133                 int totalPoints = getNumPoints() + inOtherTrack.getNumPoints();
134                 DataPoint[] mergedPoints = new DataPoint[totalPoints];
135                 System.arraycopy(_dataPoints, 0, mergedPoints, 0, getNumPoints());
136                 System.arraycopy(inOtherTrack._dataPoints, 0, mergedPoints, getNumPoints(), inOtherTrack.getNumPoints());
137                 _dataPoints = mergedPoints;
138                 // combine point count
139                 _numPoints = totalPoints;
140                 // needs to be scaled again
141                 _scaled = false;
142                 // inform listeners
143                 UpdateMessageBroker.informSubscribers();
144         }
145
146
147         /**
148          * Crop the track to the given size - subsequent points are not (yet) deleted
149          * @param inNewSize new number of points in track
150          */
151         public void cropTo(int inNewSize)
152         {
153                 if (inNewSize >= 0 && inNewSize < getNumPoints())
154                 {
155                         _numPoints = inNewSize;
156                         // needs to be scaled again
157                         _scaled = false;
158                         UpdateMessageBroker.informSubscribers();
159                 }
160         }
161
162
163         /**
164          * Delete the points marked for deletion
165          * @return number of points deleted
166          */
167         public int deleteMarkedPoints()
168         {
169                 int numCopied = 0;
170                 // Copy selected points
171                 DataPoint[] newPointArray = new DataPoint[_numPoints];
172                 for (int i=0; i<_numPoints; i++)
173                 {
174                         DataPoint point = _dataPoints[i];
175                         // Don't delete photo points
176                         if (point.getPhoto() != null || !point.getDeleteFlag())
177                         {
178                                 newPointArray[numCopied] = point;
179                                 numCopied++;
180                         }
181                 }
182
183                 // Copy array references
184                 int numDeleted = _numPoints - numCopied;
185                 if (numDeleted > 0)
186                 {
187                         _dataPoints = new DataPoint[numCopied];
188                         System.arraycopy(newPointArray, 0, _dataPoints, 0, numCopied);
189                         _numPoints = _dataPoints.length;
190                         _scaled = false;
191                 }
192                 return numDeleted;
193         }
194
195
196         /**
197          * Delete the specified point
198          * @param inIndex point index
199          * @return true if successful
200          */
201         public boolean deletePoint(int inIndex)
202         {
203                 boolean answer = deleteRange(inIndex, inIndex);
204                 return answer;
205         }
206
207
208         /**
209          * Delete the specified range of points from the Track
210          * @param inStart start of range (inclusive)
211          * @param inEnd end of range (inclusive)
212          * @return true if successful
213          */
214         public boolean deleteRange(int inStart, int inEnd)
215         {
216                 if (inStart < 0 || inEnd < 0 || inEnd < inStart)
217                 {
218                         // no valid range selected so can't delete
219                         return false;
220                 }
221                 // check through range to be deleted, and see if any new segment flags present
222                 boolean hasSegmentStart = false;
223                 DataPoint nextTrackPoint = getNextTrackPoint(inEnd+1);
224                 if (nextTrackPoint != null) {
225                         for (int i=inStart; i<=inEnd && !hasSegmentStart; i++) {
226                                 hasSegmentStart |= _dataPoints[i].getSegmentStart();
227                         }
228                         // If segment break found, make sure next trackpoint also has break
229                         if (hasSegmentStart) {nextTrackPoint.setSegmentStart(true);}
230                 }
231                 // valid range, let's delete it
232                 int numToDelete = inEnd - inStart + 1;
233                 DataPoint[] newPointArray = new DataPoint[_numPoints - numToDelete];
234                 // Copy points before the selected range
235                 if (inStart > 0)
236                 {
237                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inStart);
238                 }
239                 // Copy points after the deleted one(s)
240                 if (inEnd < (_numPoints - 1))
241                 {
242                         System.arraycopy(_dataPoints, inEnd + 1, newPointArray, inStart,
243                                 _numPoints - inEnd - 1);
244                 }
245                 // Copy points over original array
246                 _dataPoints = newPointArray;
247                 _numPoints -= numToDelete;
248                 // needs to be scaled again
249                 _scaled = false;
250                 return true;
251         }
252
253
254         /**
255          * Reverse the specified range of points
256          * @param inStart start index
257          * @param inEnd end index
258          * @return true if successful, false otherwise
259          */
260         public boolean reverseRange(int inStart, int inEnd)
261         {
262                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints)
263                 {
264                         return false;
265                 }
266                 // calculate how many point swaps are required
267                 int numPointsToReverse = (inEnd - inStart + 1) / 2;
268                 DataPoint p = null;
269                 for (int i=0; i<numPointsToReverse; i++)
270                 {
271                         // swap pairs of points
272                         p = _dataPoints[inStart + i];
273                         _dataPoints[inStart + i] = _dataPoints[inEnd - i];
274                         _dataPoints[inEnd - i] = p;
275                 }
276                 // adjust segment starts
277                 shiftSegmentStarts(inStart, inEnd);
278                 // Find first track point and following track point, and set segment starts to true
279                 DataPoint firstTrackPoint = getNextTrackPoint(inStart);
280                 if (firstTrackPoint != null) {firstTrackPoint.setSegmentStart(true);}
281                 DataPoint nextTrackPoint = getNextTrackPoint(inEnd+1);
282                 if (nextTrackPoint != null) {nextTrackPoint.setSegmentStart(true);}
283                 // needs to be scaled again
284                 _scaled = false;
285                 UpdateMessageBroker.informSubscribers();
286                 return true;
287         }
288
289
290         /**
291          * Add the given time offset to the specified range
292          * @param inStart start of range
293          * @param inEnd end of range
294          * @param inOffset offset to add (-ve to subtract)
295          * @return true on success
296          */
297         public boolean addTimeOffset(int inStart, int inEnd, long inOffset)
298         {
299                 // sanity check
300                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints) {
301                         return false;
302                 }
303                 boolean foundTimestamp = false;
304                 // Loop over all points within range
305                 for (int i=inStart; i<=inEnd; i++)
306                 {
307                         Timestamp timestamp = _dataPoints[i].getTimestamp();
308                         if (timestamp != null)
309                         {
310                                 // This point has a timestamp so add the offset to it
311                                 foundTimestamp = true;
312                                 timestamp.addOffset(inOffset);
313                         }
314                 }
315                 return foundTimestamp;
316         }
317
318         /**
319          * Add the given altitude offset to the specified range
320          * @param inStart start of range
321          * @param inEnd end of range
322          * @param inOffset offset to add (-ve to subtract)
323          * @param inFormat altitude format of offset
324          * @param inDecimals number of decimal places in offset
325          * @return true on success
326          */
327         public boolean addAltitudeOffset(int inStart, int inEnd, double inOffset,
328          Altitude.Format inFormat, int inDecimals)
329         {
330                 // sanity check
331                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints) {
332                         return false;
333                 }
334                 boolean foundAlt = false;
335                 // Loop over all points within range
336                 for (int i=inStart; i<=inEnd; i++)
337                 {
338                         Altitude alt = _dataPoints[i].getAltitude();
339                         if (alt != null && alt.isValid())
340                         {
341                                 // This point has an altitude so add the offset to it
342                                 foundAlt = true;
343                                 alt.addOffset(inOffset, inFormat, inDecimals);
344                         }
345                 }
346                 // needs to be scaled again
347                 _scaled = false;
348                 return foundAlt;
349         }
350
351
352         /**
353          * Collect all waypoints to the start or end of the track
354          * @param inAtStart true to collect at start, false for end
355          * @return true if successful, false if no change
356          */
357         public boolean collectWaypoints(boolean inAtStart)
358         {
359                 // Check for mixed data, numbers of waypoints & nons
360                 int numWaypoints = 0, numNonWaypoints = 0;
361                 boolean wayAfterNon = false, nonAfterWay = false;
362                 DataPoint[] waypoints = new DataPoint[_numPoints];
363                 DataPoint[] nonWaypoints = new DataPoint[_numPoints];
364                 DataPoint point = null;
365                 for (int i=0; i<_numPoints; i++)
366                 {
367                         point = _dataPoints[i];
368                         if (point.isWaypoint())
369                         {
370                                 waypoints[numWaypoints] = point;
371                                 numWaypoints++;
372                                 wayAfterNon |= (numNonWaypoints > 0);
373                         }
374                         else
375                         {
376                                 nonWaypoints[numNonWaypoints] = point;
377                                 numNonWaypoints++;
378                                 nonAfterWay |= (numWaypoints > 0);
379                         }
380                 }
381                 // Exit if the data is already in the specified order
382                 if (numWaypoints == 0 || numNonWaypoints == 0
383                         || (inAtStart && !wayAfterNon && nonAfterWay)
384                         || (!inAtStart && wayAfterNon && !nonAfterWay))
385                 {
386                         return false;
387                 }
388
389                 // Copy the arrays back into _dataPoints in the specified order
390                 if (inAtStart)
391                 {
392                         System.arraycopy(waypoints, 0, _dataPoints, 0, numWaypoints);
393                         System.arraycopy(nonWaypoints, 0, _dataPoints, numWaypoints, numNonWaypoints);
394                 }
395                 else
396                 {
397                         System.arraycopy(nonWaypoints, 0, _dataPoints, 0, numNonWaypoints);
398                         System.arraycopy(waypoints, 0, _dataPoints, numNonWaypoints, numWaypoints);
399                 }
400                 // needs to be scaled again
401                 _scaled = false;
402                 UpdateMessageBroker.informSubscribers();
403                 return true;
404         }
405
406
407         /**
408          * Interleave all waypoints by each nearest track point
409          * @return true if successful, false if no change
410          */
411         public boolean interleaveWaypoints()
412         {
413                 // Separate waypoints and find nearest track point
414                 int numWaypoints = 0;
415                 DataPoint[] waypoints = new DataPoint[_numPoints];
416                 int[] pointIndices = new int[_numPoints];
417                 DataPoint point = null;
418                 int i = 0;
419                 for (i=0; i<_numPoints; i++)
420                 {
421                         point = _dataPoints[i];
422                         if (point.isWaypoint())
423                         {
424                                 waypoints[numWaypoints] = point;
425                                 pointIndices[numWaypoints] = getNearestPointIndex(
426                                         _xValues[i], _yValues[i], -1.0, true);
427                                 numWaypoints++;
428                         }
429                 }
430                 // Exit if data not mixed
431                 if (numWaypoints == 0 || numWaypoints == _numPoints)
432                         return false;
433
434                 // Loop round points copying to correct order
435                 DataPoint[] dataCopy = new DataPoint[_numPoints];
436                 int copyIndex = 0;
437                 for (i=0; i<_numPoints; i++)
438                 {
439                         point = _dataPoints[i];
440                         // if it's a track point, copy it
441                         if (!point.isWaypoint())
442                         {
443                                 dataCopy[copyIndex] = point;
444                                 copyIndex++;
445                         }
446                         // check for waypoints with this index
447                         for (int j=0; j<numWaypoints; j++)
448                         {
449                                 if (pointIndices[j] == i)
450                                 {
451                                         dataCopy[copyIndex] = waypoints[j];
452                                         copyIndex++;
453                                 }
454                         }
455                 }
456                 // Copy data back to track
457                 _dataPoints = dataCopy;
458                 // needs to be scaled again to recalc x, y
459                 _scaled = false;
460                 UpdateMessageBroker.informSubscribers();
461                 return true;
462         }
463
464
465         /**
466          * Cut and move the specified section
467          * @param inSectionStart start index of section
468          * @param inSectionEnd end index of section
469          * @param inMoveTo index of move to point
470          * @return true if move successful
471          */
472         public boolean cutAndMoveSection(int inSectionStart, int inSectionEnd, int inMoveTo)
473         {
474                 // TODO: Move cut/move into separate function?
475                 // Check that indices make sense
476                 if (inSectionStart > 0 && inSectionEnd > inSectionStart && inMoveTo >= 0
477                         && (inMoveTo < inSectionStart || inMoveTo > (inSectionEnd+1)))
478                 {
479                         // do the cut and move
480                         DataPoint[] newPointArray = new DataPoint[_numPoints];
481                         // System.out.println("Cut/move section (" + inSectionStart + " - " + inSectionEnd + ") to before point " + inMoveTo);
482                         // Is it a forward copy or a backward copy?
483                         if (inSectionStart > inMoveTo)
484                         {
485                                 int sectionLength = inSectionEnd - inSectionStart + 1;
486                                 // move section to earlier point
487                                 if (inMoveTo > 0) {
488                                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inMoveTo); // unchanged points before
489                                 }
490                                 System.arraycopy(_dataPoints, inSectionStart, newPointArray, inMoveTo, sectionLength); // moved bit
491                                 // after insertion point, before moved bit
492                                 System.arraycopy(_dataPoints, inMoveTo, newPointArray, inMoveTo + sectionLength, inSectionStart - inMoveTo);
493                                 // after moved bit
494                                 if (inSectionEnd < (_numPoints - 1)) {
495                                         System.arraycopy(_dataPoints, inSectionEnd+1, newPointArray, inSectionEnd+1, _numPoints - inSectionEnd - 1);
496                                 }
497                         }
498                         else
499                         {
500                                 // Move section to later point
501                                 if (inSectionStart > 0) {
502                                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inSectionStart); // unchanged points before
503                                 }
504                                 // from end of section to move to point
505                                 if (inMoveTo > (inSectionEnd + 1)) {
506                                         System.arraycopy(_dataPoints, inSectionEnd+1, newPointArray, inSectionStart, inMoveTo - inSectionEnd - 1);
507                                 }
508                                 // moved bit
509                                 System.arraycopy(_dataPoints, inSectionStart, newPointArray, inSectionStart + inMoveTo - inSectionEnd - 1,
510                                         inSectionEnd - inSectionStart + 1);
511                                 // unchanged bit after
512                                 if (inSectionEnd < (_numPoints - 1)) {
513                                         System.arraycopy(_dataPoints, inMoveTo, newPointArray, inMoveTo, _numPoints - inMoveTo);
514                                 }
515                         }
516                         // Copy array references
517                         _dataPoints = newPointArray;
518                         _scaled = false;
519                         return true;
520                 }
521                 return false;
522         }
523
524
525         /**
526          * Interpolate extra points between two selected ones
527          * @param inStartIndex start index of interpolation
528          * @param inNumPoints num points to insert
529          * @return true if successful
530          */
531         public boolean interpolate(int inStartIndex, int inNumPoints)
532         {
533                 // check parameters
534                 if (inStartIndex < 0 || inStartIndex >= _numPoints || inNumPoints <= 0)
535                         return false;
536
537                 // get start and end points
538                 DataPoint startPoint = getPoint(inStartIndex);
539                 DataPoint endPoint = getPoint(inStartIndex + 1);
540
541                 // Make array of points to insert
542                 DataPoint[] insertedPoints = startPoint.interpolate(endPoint, inNumPoints);
543
544                 // Insert points into track
545                 return insertRange(insertedPoints, inStartIndex + 1);
546         }
547
548
549         /**
550          * Average selected points
551          * @param inStartIndex start index of selection
552          * @param inEndIndex end index of selection
553          * @return true if successful
554          */
555         public boolean average(int inStartIndex, int inEndIndex)
556         {
557                 // check parameters
558                 if (inStartIndex < 0 || inStartIndex >= _numPoints || inEndIndex <= inStartIndex)
559                         return false;
560
561                 DataPoint startPoint = getPoint(inStartIndex);
562                 double firstLatitude = startPoint.getLatitude().getDouble();
563                 double firstLongitude = startPoint.getLongitude().getDouble();
564                 double latitudeDiff = 0.0, longitudeDiff = 0.0;
565                 double totalAltitude = 0;
566                 int numAltitudes = 0;
567                 Altitude.Format altFormat = Config.getConfigBoolean(Config.KEY_METRIC_UNITS)?Altitude.Format.METRES:Altitude.Format.FEET;
568                 // loop between start and end points
569                 for (int i=inStartIndex; i<= inEndIndex; i++)
570                 {
571                         DataPoint currPoint = getPoint(i);
572                         latitudeDiff += (currPoint.getLatitude().getDouble() - firstLatitude);
573                         longitudeDiff += (currPoint.getLongitude().getDouble() - firstLongitude);
574                         if (currPoint.hasAltitude()) {
575                                 totalAltitude += currPoint.getAltitude().getValue(altFormat);
576                                 numAltitudes++;
577                         }
578                 }
579                 int numPoints = inEndIndex - inStartIndex + 1;
580                 double meanLatitude = firstLatitude + (latitudeDiff / numPoints);
581                 double meanLongitude = firstLongitude + (longitudeDiff / numPoints);
582                 Altitude meanAltitude = null;
583                 if (numAltitudes > 0) {meanAltitude = new Altitude((int) (totalAltitude / numAltitudes), altFormat);}
584
585                 DataPoint insertedPoint = new DataPoint(new Latitude(meanLatitude, Coordinate.FORMAT_NONE),
586                         new Longitude(meanLongitude, Coordinate.FORMAT_NONE), meanAltitude);
587                 // Make into singleton
588                 insertedPoint.setSegmentStart(true);
589                 DataPoint nextPoint = getNextTrackPoint(inEndIndex+1);
590                 if (nextPoint != null) {nextPoint.setSegmentStart(true);}
591                 // Insert points into track
592                 return insertRange(new DataPoint[] {insertedPoint}, inEndIndex + 1);
593         }
594
595
596         /**
597          * Append the specified points to the end of the track
598          * @param inPoints DataPoint objects to add
599          */
600         public void appendPoints(DataPoint[] inPoints)
601         {
602                 // Insert points into track
603                 if (inPoints != null && inPoints.length > 0)
604                 {
605                         insertRange(inPoints, _numPoints);
606                 }
607                 // needs to be scaled again to recalc x, y
608                 _scaled = false;
609                 UpdateMessageBroker.informSubscribers();
610         }
611
612
613         //////// information methods /////////////
614
615
616         /**
617          * Get the point at the given index
618          * @param inPointNum index number, starting at 0
619          * @return DataPoint object, or null if out of range
620          */
621         public DataPoint getPoint(int inPointNum)
622         {
623                 if (inPointNum > -1 && inPointNum < getNumPoints())
624                 {
625                         return _dataPoints[inPointNum];
626                 }
627                 return null;
628         }
629
630
631         /**
632          * @return altitude range of points as AltitudeRange object
633          */
634         public AltitudeRange getAltitudeRange()
635         {
636                 if (!_scaled) scalePoints();
637                 return _altitudeRange;
638         }
639
640         /**
641          * @return the number of (valid) points in the track
642          */
643         public int getNumPoints()
644         {
645                 return _numPoints;
646         }
647
648         /**
649          * @return The range of x values as a DoubleRange object
650          */
651         public DoubleRange getXRange()
652         {
653                 if (!_scaled) scalePoints();
654                 return _xRange;
655         }
656
657         /**
658          * @return The range of y values as a DoubleRange object
659          */
660         public DoubleRange getYRange()
661         {
662                 if (!_scaled) scalePoints();
663                 return _yRange;
664         }
665
666         /**
667          * @return The range of lat values as a DoubleRange object
668          */
669         public DoubleRange getLatRange()
670         {
671                 if (!_scaled) scalePoints();
672                 return _latRange;
673         }
674         /**
675          * @return The range of lon values as a DoubleRange object
676          */
677         public DoubleRange getLonRange()
678         {
679                 if (!_scaled) scalePoints();
680                 return _longRange;
681         }
682
683         /**
684          * @param inPointNum point index, starting at 0
685          * @return scaled x value of specified point
686          */
687         public double getX(int inPointNum)
688         {
689                 if (!_scaled) scalePoints();
690                 return _xValues[inPointNum];
691         }
692
693         /**
694          * @param inPointNum point index, starting at 0
695          * @return scaled y value of specified point
696          */
697         public double getY(int inPointNum)
698         {
699                 if (!_scaled) scalePoints();
700                 return _yValues[inPointNum];
701         }
702
703         /**
704          * @return the master field list
705          */
706         public FieldList getFieldList()
707         {
708                 return _masterFieldList;
709         }
710
711
712         /**
713          * Checks if any data exists for the specified field
714          * @param inField Field to examine
715          * @return true if data exists for this field
716          */
717         public boolean hasData(Field inField)
718         {
719                 // Don't use this method for altitudes
720                 if (inField.equals(Field.ALTITUDE)) {return hasAltitudeData();}
721                 return hasData(inField, 0, _numPoints-1);
722         }
723
724
725         /**
726          * Checks if any data exists for the specified field in the specified range
727          * @param inField Field to examine
728          * @param inStart start of range to check
729          * @param inEnd end of range to check (inclusive)
730          * @return true if data exists for this field
731          */
732         public boolean hasData(Field inField, int inStart, int inEnd)
733         {
734                 // Loop over selected point range
735                 for (int i=inStart; i<=inEnd; i++)
736                 {
737                         if (_dataPoints[i].getFieldValue(inField) != null)
738                         {
739                                 // Check altitudes and timestamps
740                                 if ((inField != Field.ALTITUDE || _dataPoints[i].getAltitude().isValid())
741                                         && (inField != Field.TIMESTAMP || _dataPoints[i].getTimestamp().isValid()))
742                                 {
743                                         return true;
744                                 }
745                         }
746                 }
747                 return false;
748         }
749
750         /**
751          * @return true if track has altitude data
752          */
753         public boolean hasAltitudeData()
754         {
755                 for (int i=0; i<_numPoints; i++) {
756                         if (_dataPoints[i].hasAltitude()) {return true;}
757                 }
758                 return false;
759         }
760
761         /**
762          * @return true if track contains at least one trackpoint
763          */
764         public boolean hasTrackPoints()
765         {
766                 if (!_scaled) scalePoints();
767                 return _hasTrackpoint;
768         }
769
770         /**
771          * @return true if track contains waypoints
772          */
773         public boolean hasWaypoints()
774         {
775                 if (!_scaled) scalePoints();
776                 return _hasWaypoint;
777         }
778
779         /**
780          * @return true if track contains any points marked for deletion
781          */
782         public boolean hasMarkedPoints()
783         {
784                 if (_numPoints < 1) {
785                         return false;
786                 }
787                 // Loop over points looking for any marked for deletion
788                 for (int i=0; i<=_numPoints-1; i++)
789                 {
790                         if (_dataPoints[i] != null && _dataPoints[i].getDeleteFlag()) {
791                                 return true;
792                         }
793                 }
794                 // None found
795                 return false;
796         }
797
798         /**
799          * Clear all the deletion markers
800          */
801         public void clearDeletionMarkers()
802         {
803                 for (int i=0; i<_numPoints; i++)
804                 {
805                         _dataPoints[i].setMarkedForDeletion(false);
806                 }
807         }
808
809         /**
810          * Collect all the waypoints into the given List
811          * @param inList List to fill with waypoints
812          */
813         public void getWaypoints(List<DataPoint> inList)
814         {
815                 // clear list
816                 inList.clear();
817                 // loop over points and copy all waypoints into list
818                 for (int i=0; i<=_numPoints-1; i++)
819                 {
820                         if (_dataPoints[i] != null && _dataPoints[i].isWaypoint())
821                         {
822                                 inList.add(_dataPoints[i]);
823                         }
824                 }
825         }
826
827
828         /**
829          * Search for the given Point in the track and return the index
830          * @param inPoint Point to look for
831          * @return index of Point, if any or -1 if not found
832          */
833         public int getPointIndex(DataPoint inPoint)
834         {
835                 if (inPoint != null)
836                 {
837                         // Loop over points in track
838                         for (int i=0; i<=_numPoints-1; i++)
839                         {
840                                 if (_dataPoints[i] == inPoint)
841                                 {
842                                         return i;
843                                 }
844                         }
845                 }
846                 // not found
847                 return -1;
848         }
849
850
851         ///////// Internal processing methods ////////////////
852
853
854         /**
855          * Scale all the points in the track to gain x and y values
856          * ready for plotting
857          */
858         private void scalePoints()
859         {
860                 // Loop through all points in track, to see limits of lat, long and altitude
861                 _longRange = new DoubleRange();
862                 _latRange = new DoubleRange();
863                 _altitudeRange = new AltitudeRange();
864                 int p;
865                 _hasWaypoint = false; _hasTrackpoint = false;
866                 for (p=0; p < getNumPoints(); p++)
867                 {
868                         DataPoint point = getPoint(p);
869                         if (point != null && point.isValid())
870                         {
871                                 _longRange.addValue(point.getLongitude().getDouble());
872                                 _latRange.addValue(point.getLatitude().getDouble());
873                                 if (point.getAltitude().isValid())
874                                 {
875                                         _altitudeRange.addValue(point.getAltitude());
876                                 }
877                                 if (point.isWaypoint())
878                                         _hasWaypoint = true;
879                                 else
880                                         _hasTrackpoint = true;
881                         }
882                 }
883
884                 // Loop over points and calculate scales
885                 _xValues = new double[getNumPoints()];
886                 _yValues = new double[getNumPoints()];
887                 _xRange = new DoubleRange();
888                 _yRange = new DoubleRange();
889                 for (p=0; p < getNumPoints(); p++)
890                 {
891                         DataPoint point = getPoint(p);
892                         if (point != null)
893                         {
894                                 _xValues[p] = MapUtils.getXFromLongitude(point.getLongitude().getDouble());
895                                 _xRange.addValue(_xValues[p]);
896                                 _yValues[p] = MapUtils.getYFromLatitude(point.getLatitude().getDouble());
897                                 _yRange.addValue(_yValues[p]);
898                         }
899                 }
900                 _scaled = true;
901         }
902
903
904         /**
905          * Find the nearest point to the specified x and y coordinates
906          * or -1 if no point is within the specified max distance
907          * @param inX x coordinate
908          * @param inY y coordinate
909          * @param inMaxDist maximum distance from selected coordinates
910          * @param inJustTrackPoints true if waypoints should be ignored
911          * @return index of nearest point or -1 if not found
912          */
913         public int getNearestPointIndex(double inX, double inY, double inMaxDist, boolean inJustTrackPoints)
914         {
915                 int nearestPoint = 0;
916                 double nearestDist = -1.0;
917                 double currDist;
918                 for (int i=0; i < getNumPoints(); i++)
919                 {
920                         if (!inJustTrackPoints || !_dataPoints[i].isWaypoint())
921                         {
922                                 currDist = Math.abs(_xValues[i] - inX) + Math.abs(_yValues[i] - inY);
923                                 if (currDist < nearestDist || nearestDist < 0.0)
924                                 {
925                                         nearestPoint = i;
926                                         nearestDist = currDist;
927                                 }
928                         }
929                 }
930                 // Check whether it's within required distance
931                 if (nearestDist > inMaxDist && inMaxDist > 0.0)
932                 {
933                         return -1;
934                 }
935                 return nearestPoint;
936         }
937
938         /**
939          * Get the next track point starting from the given index
940          * @param inStartIndex index to start looking from
941          * @return next track point, or null if end of data reached
942          */
943         public DataPoint getNextTrackPoint(int inStartIndex)
944         {
945                 return getNextTrackPoint(inStartIndex, _numPoints, true);
946         }
947
948         /**
949          * Get the next track point in the given range
950          * @param inStartIndex index to start looking from
951          * @param inEndIndex index to stop looking
952          * @return next track point, or null if end of data reached
953          */
954         public DataPoint getNextTrackPoint(int inStartIndex, int inEndIndex)
955         {
956                 return getNextTrackPoint(inStartIndex, inEndIndex, true);
957         }
958
959         /**
960          * Get the previous track point starting from the given index
961          * @param inStartIndex index to start looking from
962          * @return next track point, or null if end of data reached
963          */
964         public DataPoint getPreviousTrackPoint(int inStartIndex)
965         {
966                 return getNextTrackPoint(inStartIndex, _numPoints, false);
967         }
968
969         /**
970          * Get the next track point starting from the given index
971          * @param inStartIndex index to start looking from
972          * @param inEndIndex index to stop looking (inclusive)
973          * @param inCountUp true for next, false for previous
974          * @return next track point, or null if end of data reached
975          */
976         private DataPoint getNextTrackPoint(int inStartIndex, int inEndIndex, boolean inCountUp)
977         {
978                 // Loop forever over points
979                 int increment = inCountUp?1:-1;
980                 for (int i=inStartIndex; i<=inEndIndex; i+=increment)
981                 {
982                         DataPoint point = getPoint(i);
983                         // Exit if end of data reached - there wasn't a track point
984                         if (point == null) {return null;}
985                         if (point.isValid() && !point.isWaypoint()) {
986                                 // next track point found
987                                 return point;
988                         }
989                 }
990                 return null;
991         }
992
993         /**
994          * Shift all the segment start flags in the given range by 1
995          * Method used by reverse range and its undo
996          * @param inStartIndex start of range, inclusive
997          * @param inEndIndex end of range, inclusive
998          */
999         public void shiftSegmentStarts(int inStartIndex, int inEndIndex)
1000         {
1001                 boolean prevFlag = true;
1002                 boolean currFlag = true;
1003                 for (int i=inStartIndex; i<= inEndIndex; i++)
1004                 {
1005                         DataPoint point = getPoint(i);
1006                         if (point != null && !point.isWaypoint())
1007                         {
1008                                 // remember flag
1009                                 currFlag = point.getSegmentStart();
1010                                 // shift flag by 1
1011                                 point.setSegmentStart(prevFlag);
1012                                 prevFlag = currFlag;
1013                         }
1014                 }
1015         }
1016
1017         ////////////////// Cloning and replacing ///////////////////
1018
1019         /**
1020          * Clone the array of DataPoints
1021          * @return shallow copy of DataPoint objects
1022          */
1023         public DataPoint[] cloneContents()
1024         {
1025                 DataPoint[] clone = new DataPoint[getNumPoints()];
1026                 System.arraycopy(_dataPoints, 0, clone, 0, getNumPoints());
1027                 return clone;
1028         }
1029
1030
1031         /**
1032          * Clone the specified range of data points
1033          * @param inStart start index (inclusive)
1034          * @param inEnd end index (inclusive)
1035          * @return shallow copy of DataPoint objects
1036          */
1037         public DataPoint[] cloneRange(int inStart, int inEnd)
1038         {
1039                 int numSelected = 0;
1040                 if (inEnd >= 0 && inEnd >= inStart)
1041                 {
1042                         numSelected = inEnd - inStart + 1;
1043                 }
1044                 DataPoint[] result = new DataPoint[numSelected>0?numSelected:0];
1045                 if (numSelected > 0)
1046                 {
1047                         System.arraycopy(_dataPoints, inStart, result, 0, numSelected);
1048                 }
1049                 return result;
1050         }
1051
1052
1053         /**
1054          * Re-insert the specified point at the given index
1055          * @param inPoint point to insert
1056          * @param inIndex index at which to insert the point
1057          * @return true if it worked, false otherwise
1058          */
1059         public boolean insertPoint(DataPoint inPoint, int inIndex)
1060         {
1061                 if (inIndex > _numPoints || inPoint == null)
1062                 {
1063                         return false;
1064                 }
1065                 // Make new array to copy points over to
1066                 DataPoint[] newPointArray = new DataPoint[_numPoints + 1];
1067                 if (inIndex > 0)
1068                 {
1069                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inIndex);
1070                 }
1071                 newPointArray[inIndex] = inPoint;
1072                 if (inIndex < _numPoints)
1073                 {
1074                         System.arraycopy(_dataPoints, inIndex, newPointArray, inIndex+1, _numPoints - inIndex);
1075                 }
1076                 // Change over to new array
1077                 _dataPoints = newPointArray;
1078                 _numPoints++;
1079                 // needs to be scaled again
1080                 _scaled = false;
1081                 UpdateMessageBroker.informSubscribers();
1082                 return true;
1083         }
1084
1085
1086         /**
1087          * Re-insert the specified point range at the given index
1088          * @param inPoints point array to insert
1089          * @param inIndex index at which to insert the points
1090          * @return true if it worked, false otherwise
1091          */
1092         public boolean insertRange(DataPoint[] inPoints, int inIndex)
1093         {
1094                 if (inIndex > _numPoints || inPoints == null)
1095                 {
1096                         return false;
1097                 }
1098                 // Make new array to copy points over to
1099                 DataPoint[] newPointArray = new DataPoint[_numPoints + inPoints.length];
1100                 if (inIndex > 0)
1101                 {
1102                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inIndex);
1103                 }
1104                 System.arraycopy(inPoints, 0, newPointArray, inIndex, inPoints.length);
1105                 if (inIndex < _numPoints)
1106                 {
1107                         System.arraycopy(_dataPoints, inIndex, newPointArray, inIndex+inPoints.length, _numPoints - inIndex);
1108                 }
1109                 // Change over to new array
1110                 _dataPoints = newPointArray;
1111                 _numPoints += inPoints.length;
1112                 // needs to be scaled again
1113                 _scaled = false;
1114                 UpdateMessageBroker.informSubscribers();
1115                 return true;
1116         }
1117
1118
1119         /**
1120          * Replace the track contents with the given point array
1121          * @param inContents array of DataPoint objects
1122          * @return true on success
1123          */
1124         public boolean replaceContents(DataPoint[] inContents)
1125         {
1126                 // master field array stays the same
1127                 // (would need to store field array too if we wanted to redo a load)
1128                 // replace data array
1129                 _dataPoints = inContents;
1130                 _numPoints = _dataPoints.length;
1131                 _scaled = false;
1132                 UpdateMessageBroker.informSubscribers();
1133                 return true;
1134         }
1135
1136
1137         /**
1138          * Edit the specified point
1139          * @param inPoint point to edit
1140          * @param inEditList list of edits to make
1141          * @param inUndo true if undo operation, false otherwise
1142          * @return true if successful
1143          */
1144         public boolean editPoint(DataPoint inPoint, FieldEditList inEditList, boolean inUndo)
1145         {
1146                 if (inPoint != null && inEditList != null && inEditList.getNumEdits() > 0)
1147                 {
1148                         // remember if coordinates have changed
1149                         boolean coordsChanged = false;
1150                         // go through edits one by one
1151                         int numEdits = inEditList.getNumEdits();
1152                         for (int i=0; i<numEdits; i++)
1153                         {
1154                                 FieldEdit edit = inEditList.getEdit(i);
1155                                 Field editField = edit.getField();
1156                                 inPoint.setFieldValue(editField, edit.getValue(), inUndo);
1157                                 // Check that master field list has this field already (maybe point name has been added)
1158                                 if (!_masterFieldList.contains(editField)) {
1159                                         _masterFieldList.extendList(editField);
1160                                 }
1161                                 // check coordinates
1162                                 coordsChanged |= (editField.equals(Field.LATITUDE)
1163                                         || editField.equals(Field.LONGITUDE) || editField.equals(Field.ALTITUDE));
1164                         }
1165                         // set photo status if coordinates have changed
1166                         if (inPoint.getPhoto() != null && coordsChanged)
1167                         {
1168                                 inPoint.getPhoto().setCurrentStatus(Photo.Status.CONNECTED);
1169                         }
1170                         // point possibly needs to be scaled again
1171                         _scaled = false;
1172                         // trigger listeners
1173                         UpdateMessageBroker.informSubscribers();
1174                         return true;
1175                 }
1176                 return false;
1177         }
1178 }