Finished main logic.

Not tested.