factorize HTML formatting and added couple of checks