complete rewrite. inspired by lwpgt.