Initial PHP port from Python (incomplete)