(load-quietly-from-lib "ch3.ss")

(define poly-tag 'poly)

(define the-zero-poly (list poly-tag 0))

(define degree 
  (lambda (poly)
    (- (length poly) 2)))

(define leading-coef
  (lambda (poly)
    (let ((poly-car cadr))
      (poly-car poly))))

(define rest-of-poly
  (lambda (poly)
    (let ((poly-cdr (lambda (p) (cons poly-tag (cddr p)))))
      (cond
	((zero? (degree poly)) the-zero-poly)
	((zero? (leading-coef (poly-cdr poly)))
	 (rest-of-poly (poly-cdr poly)))
	(else (poly-cdr poly))))))

(define poly-cons
  (lambda (deg coef poly)
    (let ((deg-p (degree poly))
	  (remove-tag cdr))
      (cond
        ((and (zero? deg) (equal? poly the-zero-poly)) (list poly-tag coef))
        ((< deg-p deg)
         (if (zero? coef)
             poly
	     (cons poly-tag
		   (cons coef
			 (append (list-of-zeros (sub1 (- deg deg-p))) 
			   (remove-tag poly))))))
        (else (error "poly-cons: Degree too high in" poly))))))
