Rearranged code to prevent crash

Rearranged code to prevent a crash when called by another program.