fixes bugges and cleans up code