Align axis to longest edge

I need a simple script which for every object in the selection would find the longest edge (of its bounding box) and align any axis to this edge. I was searching for it and couldn't find anything, and with my current mxs "skills" I am not able to get my head around it. Any help would be appreciated.