fixed minor errors and more robust