Working version, finally! Now to clean up code