Finally working, though I think errors are calculated a bit wrong