Method and apparatus for controlling a ventilator are described. The invention can be used to control mechanical ventilators as well as respiratory assist devices such as CPAP machines. The apparatus receives input data indicative of patient's oxygen level. A controller determines PEEP, or CPAP, and FIO2, on the basis of data indicative of the patient's oxygen level. In an alternative embodiment, the apparatus further receives input data indicative of patient's carbon dioxide levels, respiratory elastance and airway resistance, and barometric pressure. The controller further utilizes the said input data to determine the optimal values of tidal volume and breathing frequency for a next breath of the patient, and uses the respiratory elastance and airway resistance data to determine any necessary adjustments in the I:E ratio. The controller also applies safety rules, detects and corrects artifacts, and generates warning signals when needed.