first working draft

Ugly as hell, seems to work fine though.