Refactor almost all code, using wrapped file handlers.

Except the network stuff. It will be later.