Where a general verdict is rendered or a finding by the court is made in favor of the defendant, except on a plea of not guilty by reason of insanity, a judgment of acquittal must be forthwith given. If such judgment is given, or a judgment imposing a fine only, without imprisonment for nonpayment is given, and the defendant is not detained for any other legal cause, he must be discharged, if in custody, as soon as the judgment is given, except that where the acquittal is because of a variance between the pleading and the proof which may be obviated by a new accusatory pleading, the court may order his detention, to the end that a new accusatory pleading may be preferred, in the same manner and with like effect as provided in Section 1117.