;; CS 1102: Starter file for lecture on script conversion

;;;; The define-script macro ;;;;;;;;;;;;;;;;;;;;;;;;
(define abort #f)
(let/cc grab-abort
  (set! abort grab-abort))

(define-syntax define-script
  (syntax-rules ()
    [(define-script (script-name arg ...) body)
     (define (script-name arg ...)
       (abort body))]))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; a common "web form" with a single input

(define (prompt-read promptstr)
  (begin (printf (format "~a: " promptstr))
         (read)))

;;;;; the age/vote program ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; age-page-nonweb : -> void
;; displays ability to vote based on user's age
(define (age-page-nonweb)
  (let [(age (prompt-read "Enter your age"))]
    (cond [(>= age 18) (printf "Don't forget to vote!")]
          [else (printf "You'll be able to vote in ~a years" (- 18 age))])))

;;;;;;;; the adder (a bit cleaner) ;;;;;;;;;;;;;;;;;;;;;;;;

(define (clean-adder)
  (printf "sum: ~a~n" (+ (prompt-read "First number")
                         (prompt-read "Second number"))))

;;;;;;;; the tip calculator ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; helper function
(define (add-tip bill)
  (+ bill (* bill (/ (prompt-read "Enter tip percentage") 100))))

; the main function
(define (tip-adder)
  (add-tip (prompt-read "Enter bill amount")))

;;;;;;;;; fight instigator ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define (start-fight)
  (begin (prompt-read (format "In how many games should the ~a win the series? " 
                              (prompt-read "Who should win the World Series? ")))
         (printf "Dream on!~n")))

;;;;;;;; tallying charges ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define (tally item-list)
  (cond [(empty? item-list) 0]
        [else (+ (prompt-read 
                  (format "Enter cost for ~a" (first item-list)))
                 (tally (rest item-list)))]))

;;;;;;; tracking accounts ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define account
  (let ([balance 0])
    (lambda ()
      (begin
	(printf "Current balance: ~a; " balance)
        (set! balance 
              (+ balance 
                 (prompt-read "Change by")))
        (account)))))

;;;;;;; reading many web inputs ;;;;;;;;;;;;;;;;;;;;;;;;;;

;; leave prompt-read as a helper -- turn only prompt-read-many into a script

(define (prompt-read-many promptlist)
  (cond [(empty? promptlist) empty]
        [(cons? promptlist) 
         (cons (prompt-read (first promptlist))
               (prompt-read-many (rest promptlist)))]))

