Move CD check into function

Needs to be in a function or will cause fatal error.