improved logic for header detection