Mavericks 'close the clam' woes
This is almost certainly hardware related. The magnetic reed switch (or hall effect sensor) depending on vintage of the Mac is faulty or failing and potentially voltage fluctuations due to sleeping are affecting it as well.

Any chance you have had it looked at by a tech?