A man caught masturbating in the ''Teen Space'' of the Dunedin Library was on bail on a charge of rape at the time, a court has heard.
The 38-year-old cannot be named because he is yet to face trial on the sexual violation charge.
He appeared in the Dunedin District Court yesterday after admitting a charge of doing an indecent act and was jailed for four months.
The court heard the defendant was behind bars anyway, because his bail was revoked after the lewd incident.
The man walked into the library on the afternoon of March 30 and made straight for the area on the second floor reserved for teenagers.
''It was premeditated ... otherwise you would not have gone to that area,'' Judge Emma Smith pointed out.
Half an hour later, the defendant positioned himself behind a large bookshelf, 3m from a girl who was on a beanbag, reading.
He covered his crotch with a book and masturbated, leaving the scene two minutes later.
The teenage girl was oblivious to the act but library staff had spotted it.
When he was shown a replay on CCTV, the defendant acknowledged he was the man on camera but denied he was masturbating.
''It was too embarrassing to talk about,'' he told police.
However, when the matter came before the court, the man pleaded guilty immediately.
His counsel, Sarah Saunderson-Warner, said the rape charge looming over him had been ''hugely distressing''.
The resulting anxiety and depression had produced the indecent act, she said.
As far as excuses went it was ''a poor one'', Judge Smith said.
Saunderson-Warner said the girl on the beanbag had been unaware of the offending and that her client had no similar previous convictions.
Regardless, the judge said the facts were ''disturbing''.
She imposed name suppression so the man's fair-trial rights were preserved but the order will lapse once his trial - which will be held outside Dunedin - is completed.
He will appear in court again in November.