completed neural network algorithm (needs checking)