In habeas corpus proceedings, if it appears that the party has been legally committed for any public offense or that he is guilty of such an offense, although his commitment was irregular, he may be remanded to the custody or restraint from which he was taken if the person under whose custody or restraint he was is legally entitled thereto; but, if not so entitled, he must be committed to the custody or restraint of the proper officer or person.
Ala. Code § 15-21-25 (1975)