Added gradient method and cleaned up a bit of code.