The present invention provides a method and apparatus for providing continuous positive airway pressure for treating sleep apnea. The method comprises the steps of providing a breathing gas flow to a subject, measuring a respiratory characteristic of the subject, determining or estimating a preferable breathing gas flow for the subject based on wavelet analysis utilizing in part the respiratory characteristic of the subject, and preferably adjusting the breathing gas flow if the determined or estimated preferable breathing gas flow is different. This method and apparatus can be used in a number of applications including both clinical and home use in the form of CPAP for the treatment of sleep apnea or less preferably as a ventilator to assist in patient breathing.