Updated code to fix timing issues