improved header detection algorithm