Gave in and implemented goto3's solution.
Will work on solving the wrapping problem later.