Completeley rewritten program. Need to be tested.