cleaned up code and added small optimization