almost fully rewritten