the old code was kind of impossible to understand by reading it, so this is hopefully considerably clearer