Is it possible to override automatic screen orientation? Very often I use my phone lying in bed (with phone camera facing the ceiling) and the orientation changes drive me crazy. Literally if I turn the phone a few degrees it will go from portait to landscape and vice versa. 

I can disable auto-rotation, but it's not desirable in some scenarios, like when i turn on my shoulder and I want the orientation to change.

Basically, is it possible to write your own logic for screen rotation and make it run on system wide scope?

UPD: I do not want to toggle auto-rotation. I want to rewrite that logic that based on current sensor setting changes the screen orientation on system level.
This widget works well... No customer rom or root required. :0)