Cleaned up code, untested