Awesome! Thank you very much for the script. I came across this situation couple of times for Linux and HP-UX. I scratched my head, tried to guesstimate, and gave up at last.
Just to let you know, although I can make up what the script is actually doing, it would be very helpful, if you comment it properly so that others can understand and use the similar idea in different platforms.