             prevDy = CGFloat(next.value - cur.value) * intensity;
             
             cur = entries[minx + 1];
-            next = entries[minx + (size - minx > 2 ? 2 : 1)];
+            next = entries[minx + (entries.count - minx > 2 ? 2 : 1)];
             curDx = CGFloat(next.xIndex - prev.xIndex) * intensity;
             curDy = CGFloat(next.value - prev.value) * intensity;
             
             // the first cubic
-            CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
-            
-            for (var j = minx + 2; j < size - 1; j++)
+            CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix,
+                CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
+                CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY,
+                CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
+            
+            for (var j = minx + 2, count = min(size, entries.count - 1); j < count; j++)
             {
                 prevPrev = entries[j - 2];
                 prev = entries[j - 1];

            
            if (size > entries.count - 1)
            {
                cur = entries[entries.count - 1];
                prev = entries[entries.count - 2];
                prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)];
                next = cur;
                
                prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity;

                    (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
            }
        }
        
        CGContextSaveGState(context);
        
