Reformatted code and fixed upside down logic