Some refactoring, added error checking, writes response to temp file based on OS