restructured code, planned to make it somewhat portable