it would be much faster if you replace the following two while loops with an array copy (potentially with unsafe - but that's for another day)