Rearranged the order to not do unnecessary calculations or memory usage