Preliminary working version. Still not ideal
Fixed a few errors, new working version