fixed an extra space issue
and added empty index prevention