As ventilator already said, probably it would be more efficient to use a stable library for this. But I also have to note, that doing it yourself is also a fascinating task. At least that's what gets me motivated to do such things.
Perhaps you don't mind to share the source of your conversion?