(with_import "./collections.kp"
(let (
    to_bpm (lambda (x) (let (
        rows (len x)
        cols (len (idx x 0))
        file "P1"
        file (str file "\n" cols " " rows)
        file (foldl (lambda (a row)
            (str a "\n" (foldl (lambda (a x)
                (str a " " x)
            ) "" row))
        ) file x)
    ) file))

	stack concat

	side (lambda (a b) (foldl (lambda (a b c) (concat a [(concat b c) ]))
							  [] a b))

    padding (rec-lambda recurse (r c)
		(cond (and (= 1 r) (= 1 c)) [ [ 0 ] ]
              (= 1 c) (let (x (recurse (/ r 2) c)) (stack x x))
              true    (let (x (recurse r (/ c 2))) (side x x))))

	shape [ [ 1 1 ]
            [ 1 1 ] ]

	sierpinski (rec-lambda recurse (depth) 
		(if (= depth 1) shape
			  (let (s (recurse (/ depth 2))
					p (padding depth (/ depth 2))
                    ) (stack (side (side p s) p)
                             (side s s))))
    )

    img (to_bpm (sierpinski 64))
) (write_file "./sierpinski.pbm" img)
))
