(load "assert.scm")
;(load "basic-streams.scm")
;(load "delay-force.scm")
(load "ones.scm")
(load "stream-add.scm")
(load "stream-scale.scm")
(load "stream-delay.scm")
(load "stream-smooth.scm")
(load "stream-edges.scm")

(load "pnm.scm") 
; Supplies (image->pgm-file img fname) (pgm-file->image fname)
; An image is a stream where each element represents a row of pixels.  This
; row of pixels is in turn a stream of grayscale values from 0 to 1 where 0
; is black and 1 is white.

;;;;; SMOOTHING ;;;;;;;;

; Applies a stream filter to each row of an image
(define (filter-image-rows img filter)
  (if (null? img)
      '()
      (cons-stream (filter (stream-car img))
                   (filter-image-rows (stream-cdr img) filter))))

;; Use stream-smooth on each row of the image
(define (img-horiz-smooth img)
  (filter-image-rows img stream-smooth))
  
; Applies a given procedure to every pixel in an image to produce a new
; image.  Think of this as a two-dimensional version of map that works
; with a lazy-memoized image.
(define (image-map proc img)
  (if (null? img)
      '()
      (cons-stream (stream-map proc (stream-car img))
                   (image-map proc (stream-cdr img)))))
                  
; Filtering operations often produce values outside the normal valid range
; of pixel values.  Here we "clamp" intensity values to be between 0 and 1.0,
; inclusive.
(define (clamp-image img)
  (image-map (lambda (x) (min 1. x))
             (image-map (lambda (x) (max 0. x)) img)))
  
; Load our image
(define img (pgm-file->image "hitchhiker-orig.pgm"))

; Save it (good for testing
(image->pgm-file img "hitchhiker-rewrite.pgm")

; Smooth once
(image->pgm-file (clamp-image (img-horiz-smooth img)) "hitchhiker-smoothed.pgm")

; Smooth a bunch
(image->pgm-file (clamp-image (img-horiz-smooth (img-horiz-smooth 
  (img-horiz-smooth (img-horiz-smooth (img-horiz-smooth (img-horiz-smooth 
    (img-horiz-smooth img)))))))) "hitchhiker-super-smoothed.pgm")

;;;;; EDGE DETECTION ;;;;;;;;

;; Use stream-smooth on each row of the image
(define (img-vert-edges img)
  (filter-image-rows img stream-edges))
  
(image->pgm-file (clamp-image (img-vert-edges img)) "hitchhiker-vedges.pgm")

(define (mystery stream)
  (if (null? stream) '()
    (cons-stream 
      (stream-car stream)
      (cons-stream 
        (stream-car stream)
        (mystery (stream-cdr stream))))))
        
(define (image-mystery img)
  (filter-image-rows img mystery))
  
(image->pgm-file (image-mystery img) "hitchhiker-zmystery.pgm")

(image->pgm-file (mystery (image-mystery img)) "hitchhiker-zmystery2.pgm")