Cleaned up the implementation significantly