An algorithm for measuring the breathing of a patient for diagnosing breathing disorders and for controlling a breathing aid device for treating a patient. Sensors record pressure and flow rates of air delivered to a patient. The data is statistically manipulated to find the start of a breath, the end of a breath, the duration of a breath, the shape of a breath, the volume of a breath, the breathing rates, flow rates, snoring index, flattening index, and other useful data to diagnose and treat a patient. The data is used to diagnose the condition of a patient and to control a breathing aide device for treating a patient at the most optimal pressures and flow rates for the patients condition. Inspiration and expiration data are tracked separately and compared throughout the algorithm as a check the accuracy of the data manipulation by the algorithm.