Second try. sp2.cpp contains a function that does a much better job of mimicing the old code, and it might even be windows-compatible (only simple tests have been performed