(require (planet "ode-initval.ss" ("williams" "science.plt")))
(require (lib "plot.ss" "plot"))

(define (func t y f params)
  (let ((mu (car params))
        (y0 (vector-ref y 0))
        (y1 (vector-ref y 1)))
    (vector-set! f 0 y1)
    (vector-set! f 1 (- (- y0) (* mu y1 (- (* y0 y0) 1.0))))))

(define (main)
  (let* ((type rk4-ode-type)
         (step (make-ode-step type 2))
         (control (control-y-new 1.0e-6 0.0))
         (evolve (make-ode-evolve 2))
         (mu 10.0)
         (system (make-ode-system func #f 2 (list mu)))
         (t (box 0.0))
         (t1 100.0)
         (h (box 1.0e-6))
         (y #(1.0 0.0))
         (y0-values '())
         (y1-values '()))
    (let loop ()
      (if (< (unbox t) t1)
             evolve control step system
             t t1 h y)
            ;(printf "~a ~a ~a~n" (unbox t) (vector-ref y 0) (vector-ref y 1))
            (set! y0-values (cons (vector (unbox t) (vector-ref y 0)) y0-values))
            (set! y1-values (cons (vector (unbox t) (vector-ref y 1)) y1-values))
    (printf "Number of iterations   = ~a~n" (ode-evolve-count evolve))
    (printf "Number of failed steps = ~a~n" (ode-evolve-failed-steps evolve))
    (printf "~a~n" (plot (points (reverse y0-values))
                         (x-min 0.0)
                         (x-max 100.0)
                         (y-min -2.0)
                         (y-max 2.0)))
    (printf "~a~n" (plot (points (reverse y1-values))
                         (x-min 0.0)
                         (x-max 100.0)))