         let phaseX = animator.phaseX
         let phaseY = animator.phaseY
         
-        CGContextSaveGState(context)
-        
-        //Searching for a range with non-nil entries
-        var fromEnty: ChartDataEntry?
-        var toEntry: ChartDataEntry?
-        for x in (self.minX...self.maxX) {
-            let entry = dataSet.entryForXIndex(x)
-            if let e = entry {
-                if fromEnty == nil {
-                    fromEnty = e
-                }
-                toEntry = e
-            } else if toEntry != nil {
-                break
-            }
-        }
-        
-        guard let fromIndex = fromEnty.map({dataSet.entryIndex(entry: $0) }),
-            toIndex = toEntry.map({dataSet.entryIndex(entry: $0) }) else {
-                CGContextRestoreGState(context)
-                return
-        }
+        
+        guard let (fromIndex, toIndex) = getFirstAndLastIndex(dataSet) else { return }
         
         let diff = (fromIndex == toIndex) ? 1 : 0
         let minx = max(fromIndex - diff, 0)
         let maxx = min(max(minx + 2, toIndex + 1), entryCount)
         
+        CGContextSaveGState(context)
+
         // more than 1 color
         if (dataSet.colors.count > 1)
         {

        CGContextRestoreGState(context)
    }
    
    public func drawCubic(context context: CGContext, dataSet: ILineChartDataSet)
    {
        guard let
            trans = dataProvider?.getTransformer(dataSet.axisDependency),
            animator = animator
            else { return }
        
        let entryCount = dataSet.entryCount
        
        //Searching for a range with non-nil entries
        var fromEnty: ChartDataEntry?
        var toEntry: ChartDataEntry?
        for x in (self.minX...self.maxX) {

                
                let entryCount = dataSet.entryCount
                
                guard let (fromIndex, toIndex) = getFirstAndLastIndex(dataSet) else { return }

                
                let diff = (fromIndex == toIndex) ? 1 : 0
                let minx = max(fromIndex - diff, 0)
