rewritten for php 5.3, use global state, simplified