Reorganized

Moved things into functions. Still some duplicate code. Also updated
the postgres schema