This is an very common and well understood problem. Take a look at this:
http://www.varlena.com/GeneralBits/130.php
-- Regards,Peter Geoghegan