cleaned the code a bit for better error msgs and better debugging