Witnesses may be compelled to attend and testify before the grand jury; and witnesses on behalf of the state, or of the defendant, in a criminal prosecution, may be compelled to attend and testify in open court, if they have been subpoenaed, without their fees being first paid or tendered, unless otherwise provided by law; the court may, upon the motion of the prosecuting attorney or defense counsel, recognize witnesses, with or without sureties, to attend and testify at any hearing or trial in any criminal prosecution in any court of this state, or before the grand jury. In default of such recognizance, or in the event that surety is required and has not been obtained, the court shall require the appearance of the witness before the court and shall appoint counsel for the witness if he is indigent and then shall determine that the testimony of the witness would be material to either the prosecution or the defendant and that the witness would not attend the trial of the matter unless detained and, therefore, the court may direct that such witness shall be detained in the custody of the sheriff until the hearing or trial in which the witness is to testify: PROVIDED, That each witness detained for failure to obtain surety shall be paid, in addition to witness fees for actual appearance in court, for each day of his detention a sum equal to the daily jury fee paid to a juror serving in a superior court; and each witness in breach of recognizance and who is detained therefor shall be paid, in addition to witness fees for actual appearance in court, the sum of one dollar for each day of his detention. Any such witness shall be provided food and lodging while so detained. Any person accused of any crime in this state, by indictment, information, or otherwise, may, in the examination or trial of the cause, offer himself, or herself, as a witness in his or her own behalf, and shall be allowed to testify as other witnesses in such case, and when accused shall so testify, he or she shall be subject to all the rules of law relating to cross-examination of other witnesses: PROVIDED, That nothing in this code shall be construed to compel such accused person to offer himself or herself as a witness in such case.