There are tons of proven, tested libraries for this.
The dumb, successful approach would be to use one of them.