added most of the code