BTW... the script should make a temp hash with layer names as the keys and visibility as the values. This should store the visible state of layers before rendering starts.
.. do your thing ...
.. then restore the visibilty state for all layers at the end.