Added error check and directory validation