Implemented all the logic I can think of. Needs testing. Some things could be integrated. Needs reorganizing and commenting.
Bug fixes of previoius commit