         
         let visibleBounds = pagingScrollView.bounds
         var index = Int(floor(visibleBounds.midX / visibleBounds.width))
-        if index < 0 {
-            index = 0
-        }
-        if index > (numberOfPhotos() - 1) {
-            index = numberOfPhotos() - 1
-        }
+        index = max(0, min(numberOfPhotos() - 1, index))
         
         let previousCurrentPageIndex = _currentPageIndex
         _currentPageIndex = index

        
        visiblePages.removeAll()
        
        pagingScrollView.contentOffset = contentOffsetForPage(AtIndex: _currentPageIndex)
        createPages()
    }
    

        return CGSize(width: bounds.size.width * CGFloat(numberOfPhotos()), height: bounds.size.height)
    }
    
    private func contentOffsetForPage(atIndex index: Int) -> CGPoint {
        let pageWidth = pagingScrollView.bounds.size.width
        let newOffset = CGFloat(index) * pageWidth
        return CGPoint(x: newOffset, y: 0)
    }
    
    private func centerContentOffsetToMiddleSegment() {
        if numberOfPhotos() == 0 { return }
        
        _currentPageIndex = (_currentPageIndex % realNumberOfPhotos()) + realNumberOfPhotos()
        let pageFrame = frameForPage(atIndex: _currentPageIndex)
        
        pagingScrollView.setContentOffset(CGPoint(x: pageFrame.origin.x - PADDING, y: 0), animated: false)
    }
