unified html generation code and improved error handling