A 39-year-old San Rafael man pleaded guilty Thursday to having sex with a teenage girl after she recanted accusations of rape.

Maco Maudilio Zacaria Garcia faces up to two years in jail but avoided a prison sentence. However, he is also being detained on a federal immigration hold and could be deported to his native Guatemala.

Zacaria was arrested in July after an investigation by the San Rafael Police Department. Police said the alleged crimes against the girl, a 17-year-old acquaintance, occurred in several incidents over the summer.

The district attorney's office charged Zacaria with three counts of forcible rape and a dozen other counts, including lewd acts with a child, sexual battery, false imprisonment and unlawful sex with a minor. Zacaria pleaded not guilty.

During the preliminary examination of the evidence last month, the girl took the stand and reversed herself on the allegations of forced sex. The hearing was postponed while the prosecution reconsidered its position, and Zacaria was offered a plea deal.

Zacaria accepted the deal Thursday before Judge James Chou, admitting to unlawful sex with a minor and two other counts. The rest of the charges were dismissed.

Zacaria's defense attorney, Jon Rankin, said his client had always acknowledged having sex with the girl, but said it was consensual.

"It was unfortunate that he had to suffer in jail with the allegations as they were, waiting for the girl to come forward and tell the truth," Rankin said.

The sentencing hearing is pending. Zacaria might be required to register as a sex offender for life, said Deputy District Attorney Nicole Pantaleo.