complete rewrite, no more str->int conversion
updated error checking