(in-package "ACL2")

(defmacro i-max ()
  (expt 2 (1- 28)))

(defmacro plus-nil-inf (x y)
  `(the (signed-byte 28)
        (let ((x ,x)
              (y ,y))
          (declare (type (signed-byte 28) x y))
          (cond ((or (< x 0)
                     (< y 0))
                 -1)
                (t (let ((result
                          (the (signed-byte 29) (+ x y))))
                     (declare (type (signed-byte 29) result))
                     (cond ((>= result (i-max)) -1)
                           (t (the (signed-byte 28) result)))))))))

(defmacro min-nil-inf (x y)
  `(the (signed-byte 28)
        (let ((x ,x)
              (y ,y))
          (declare (type (signed-byte 28) x y))
          (cond ((< x 0)
                 (cond ((< y 0) -1)
                       (t y)))
                ((< y 0)
                 x)
                (t
                 (the (signed-byte 28) (min x y)))))))

(defun small-integerp (x)
  (declare (xargs :guard t))
  (and (integerp x)
       (< x (i-max))
       (<= (- (i-max)) x)))

(defun small-integer-listp (list)
  (declare (xargs :guard t))
  (if (consp list)
      (and (small-integerp (car list))
           (small-integer-listp (cdr list)))
    t))

(defun small-integer-list-listp (list)
  (declare (xargs :guard t))
  (if (consp list)
      (and (small-integer-listp (car list))
           (small-integer-list-listp (cdr list)))
    t))

(defun map-to-small-integer-list-listp (list)
  (declare (xargs :guard t))
  (if (consp list)
      (and (consp (car list))
           (small-integer-list-listp (cdar list))
           (map-to-small-integer-list-listp (cdr list)))
    t))

(defun good-len-list (n list)
  (declare (xargs :guard t))
  (if (consp list)
      (and (equal (len (car list)) n)
           (good-len-list n (cdr list)))
    t))

(defun good-len-lists (list1 list2)
  (declare (xargs :guard t))
  (if (consp list1)
      (and (good-len-list (len (car list1)) (cdr list1))
           (good-len-list (len (car list1)) list2))
    t))

(defun good-len-list-mapping (n maplist)
  (declare (xargs :guard t))
  (if (consp maplist)
      (and (consp (car maplist))
           (consp (cdar maplist))
           (equal (len (cadar maplist)) n)
           (good-len-list-mapping n (cdr maplist)))
    t))

(defun good-len-lists-mapping (maplist list2)
  (declare (xargs :guard t))
  (if (consp maplist)
      (and (consp (car maplist))
           (consp (cdar maplist))
           (good-len-list (len (cadar maplist)) list2)
           (good-len-list-mapping (len (cadar maplist)) (cdr maplist)))
    t))

(defun matching-lens (list1 list2)
  (declare (xargs :guard t))
  (if (consp list1)
      (and (consp list2)
           (equal (len (car list1))
                  (len (car list2)))
           (matching-lens (cdr list1)
                          (cdr list2)))
    (not (consp list2))))