optimised homework 6 a bit. still needs more work