Initial version of code. Needs testing!