tidying up the code a bit, fixed a couble bugs