You can use some math and lisp features to get rid of a lot of lines in your code.
For example, instead of drawing a line at 0.0 elevation and then move it to hig, you can just calculate p3 as
(setq p3 (polar (list (car sp) (cadr sp) hig) nosangr (/ idimb 2)))
Next, p4 will follow the same elevation.
Back to your problem, I guess the easiest way for you to calculate p23 is using UCS.
At the beginning, set sp as 3Dpoint, otherwise everything is calculated in xOy plan (distances, angles) and you need 3d points for your 3d problem.
(setq sp (list 25.0 25.0 0.0))
Add the next code in the end of your routine, exactly between ".ucs" and ".zoom"
(command ".ucs" "world")
(setq p3 (list (car p3) (cadr p3) hig)
p4 (list (car p4) (cadr p4) hig)
)
(command ".ucs" "3p" p1 p4 p3)
(setq a (angle '(0 0 0) (trans p3 0 1)))
(command ".ucs" "world")
(setq p23 (polar p21 (+ (angle p21 p24) a) (distance p1 p3)))
(command ".line" p21 p23 p24 "")
(command ".zoom" "all" )