ugly but working error handling and better indentation