Align UVW Map modifier to longest edge in mesh?

Hi,

I've been working on a custom script that will allow for easy texturing of many timber planks in my scene.

So far i've taken some code from many helpful comments here on scriptspot and come up with this: (Please excuse the formatting, i'm not educated in maxscript)

for o in selection do (
 
	if isvalidnode o == true then
	(   
		---- Switch to modify panel, collapse objects to editable poly, select all edges.
			max modify mode
			addModifier o (Edit_Poly ())
			maxOps.CollapseNodeTo o 1 true
			subObjectLevel = 2
			actionMan.executeAction 0 "40021"
			selEdgesBA = polyop.getEdgeSelection o
			if selEdgesBA.numberset != 0 then
				---- Find the longest edge and select it.
			(
				longestEdge = undefined
				minLength = 0
				for ed in selEdgesBA do
				(
					edgeVertsArr = polyop.getEdgeVerts o ed
					edgeLength = distance (polyop.getVert o edgeVertsArr[1]) (polyop.getVert o edgeVertsArr[2])
					if edgeLength > minLength do
					(
						minLength = edgeLength
						longestEdge = ed
					)
				)
				polyop.SetEdgeSelection o longestEdge
 
				addModifier o (Uvwmap ())  ---Add UVW Map modifier and set to Box Map
				o.modifiers[#UVW_Map].maptype = 4
				o.modifiers[#UVW_Map].height = 5
				o.modifiers[#UVW_Map].length = 5
				o.modifiers[#UVW_Map].width = 5
				subobjectLevel = 1
 
				--- Now I need to align the Z Axis of the UVW Map Modifier gizmo with the longest edge. How?
 
			)
			else
				messagebox "You must have edges selected" title:"No Edges Selected"
	) else (print "no geometry selected")
 
 
)
 
 
	completeredraw()
 
 
<code>
 
All the script does for now is select the longest edge in the current editable poly.
 
 
What I'm stumped on is how to get the gizmo of a UVW Map modifier to align with this edge. Basically align the Z-Axis of the gizmo with the length of the edge.
 
Has anyone done this before and willing to share some wisdom?