slightly wonky Fortran implementation, but it works! (tested on itself)