                (if (> val max) val max))))))
 
 (defn rescale-range [ range factor ]
-  (let [ scaled-delta (* (/ (- factor 1) 2) (- (:max range) (:min range) )) ]
+  (let [ scaled-delta (* (/ (- factor 1) 2) (range-magnitude range)) ]
     {:max (+ (:max range) scaled-delta)
      :min (- (:min range) scaled-delta)}))
 


(defn draw-frame [ ctx w h ]
  (with-preserved-ctx ctx
    (.beginPath ctx)
    (aset ctx "lineWidth" 1)
    (aset ctx "strokeStyle" "#000000")
    (.moveTo ctx 0.5 0.5)
    (.lineTo ctx 0.5 (- h 0.5))
    (.stroke ctx)))

(defn draw [ ctx w h data begin-t end-t]
  (draw-series-background ctx w h)

                 (map #(vector % (* pixels-per-y-label (/ magnitude %)))
                      y-line-intervals)))))

(defn set-stroke-style [ ctx style-name ]
  (if-let [ style (get stroke-styles style-name false) ]
    (do
      (aset ctx "lineWidth" (:line-width style))      
      (aset ctx "strokeStyle" (:stroke-style style))
      (.setLineDash ctx (:line-dash style)))
    (.error js/console "Unknown stroke style:" (pr-str style-name))))

(defn draw-y-grid-line [ ctx w y value emphasize? ]
  (with-preserved-ctx ctx
    (draw-ylabel ctx (format-ylabel value) -2 y)
    (set-stroke-style ctx (if emphasize? :grid-emphasis :grid))
    (draw-line ctx [ 0 y ] [ w y ])))

(defn draw-y-grid [ ctx w h y-range ]
  (with-preserved-ctx ctx
    (let [ty (translate-fn-invert y-range h)
          y-interval (find-y-grid-interval h y-range)]
      (if (range-contains-zero? y-range)
        (let [positive-lines (floor (/ (:max y-range) y-interval))
              negative-lines (floor (/ (- (:min y-range)) y-interval))]
          (draw-y-grid-line ctx w (pixel-snap (ty 0.0)) 0.0 true)
          (doseq [ii (range positive-lines)]
            (draw-y-grid-line ctx w (pixel-snap (ty (* y-interval (+ ii 1)))) (* y-interval (+ ii 1)) false))
          (doseq [ii (range negative-lines)]
            (draw-y-grid-line ctx w (pixel-snap (ty (* (- y-interval) (+ ii 1)))) (* (- y-interval) (+ ii 1)) false)))
        (let [ lines (floor (/ (range-magnitude y-range) y-interval))]
          (doseq [ii (range lines)]
            (draw-y-grid-line ctx w (pixel-snap (ty (+ (:min y-range) (* y-interval (+ ii 1)))))
                              (+ (:min y-range) (* y-interval (+ ii 1))) false)))))))

(defn draw-series [ ctx w h data x-range ]
  (with-preserved-ctx ctx
    (set-stroke-style ctx :series-line)

    (aset ctx "font" "12px Arial")
    (let [y-range (rescale-range (s-yrange data) 1.2)]
      (unless (empty? data)
