refactored the code a bit to prepare for backprop