;; CALTECH CS 1 Fall 2007
;; Scheme code used in Lecture 18 (11/28/07)
;; mvanier@cs.caltech.edu, donnie@cs.caltech.edu
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; operations in terms of gates
(define (xor2 a b)
  (and2 (not (and2 a b))
        (not (and2 (not a) (not b)))))
(define (sum_bit a b cin)
  (xor2 (xor2 a b) cin))
(define (carry_out a b cin)
  (not (and2 (not (and2 a b))
             (and2 (not (and2 b cin))
                   (not (and2 a cin))))))

;; a simple "generic" gate
(define (prog2gate1 a b s)
  (or (and s (and a b))
      (and (not s) (or a b))))

;; more elaborate "generic" gate
(define (prog2gate a b s0 s1 s2)
  (or (and s0 s1 s2             (and a b))
      (and s0 s1 (not s2)       (not (and a b)))
      (and s0 (not s1) s2       (or a b))
      (and s0 (not s1) (not s2) (not (or a b)))
      (and (not s0) s1 s2       (xor a b))
      (and (not s0) s1 (not s2) (not (xor a b)))))

;; multiplexers
(define (mux2 a b s)
  (or (and (not s) a)
      (and s b)))
(define (mux4 a b c d s0 s1)
  (mux2 (mux2 a b s0) 
	(mux2 c d s0)
	s1))

;; multiplexers as programmable gates
(define (or2 a b)   (mux4 #f #t #t #t a b))
(define (xor2 a b)  (mux4 #f #t #t #f a b))
(define (nand2 a b) (mux4 #t #t #t #f a b))

;; CALTECH CS 1 Fall 2007
;; Machine code used in Lecture 18 (11/28/07)
;; mvanier@cs.caltech.edu, donnie@cs.caltech.edu
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; sample ALU operations
ADD  00011000 00010100 = 00101100
SUB  00011000 00010100 = 00000100
INV  00011000 XXXXXXXX = 11100111
OR   00011000 00010100 = 00011100
AND  00011000 00010100 = 00010000
XOR  00011000 00010100 = 00001100
SLL  00011000 XXXXXXXX = 00110000
SRL  00011000 XXXXXXXX = 00001100

;; some operation encodings
ADD    0000
SUB    0010
INV    0001
OR     1001
AND    1000
XOR    0110	
SLL    1110
SLR    1100

;; example
;;  C = (A+2B) & 00001111
Compute 2B (B + B)   0000 1 001 001 010
Add A and 2B         0000 1 000 010 011
And sum with mask    1000 1 011 100 111
;; in memory:
000:  0000 1 001 001 010
001:  0000 1 000 010 011
010:  1000 1 011 100 111
