Straightforward sequential version

TODO: parallelize code, most likely with chunks and pmap