first version of code reviewed and rewritten.