Cleaned up the code and removed some duplicate stuff