Finished rewrite into more proper structure, but still lots of
inefficiencies.