+BlockIter TrackIter::block_iter() const
+{
+ if(!_track)
+ return BlockIter();
+
+ Block &block = _track->get_block();
+ const vector<Block::Endpoint> &beps = block.get_endpoints();
+
+ // See if this track matches an endpoint in the block
+ for(unsigned i=0; i<beps.size(); ++i)
+ if(beps[i].track==_track && beps[i].track_ep==_entry)
+ return BlockIter(&block, i);
+
+ if(!_track->get_type().is_turnout())
+ {
+ /* Since there was no endpoint match, the preceding track can't be in a
+ different block. */
+ TrackIter rev = flip();
+ TrackIter last;
+ while(rev && &rev.track()->get_block()==&block)
+ {
+ last = rev;
+ rev = rev.next();
+ }
+
+ // If we ran out of tracks, return an empty iterator
+ if(!rev)
+ return BlockIter();
+
+ TrackIter fwd = last.reverse();
+ for(unsigned i=0; i<beps.size(); ++i)
+ if(beps[i].track==fwd.track() && beps[i].track_ep==fwd.entry())
+ return BlockIter(&block, i);
+ }
+
+ throw logic_error("internal error (didn't find block entry endpoint)");
+}
+