Major code overhaul

Almost every file has been modified to some extent. Complete recommit.