somewhat better error handling, not perfect yet