I have this short code that uses the \aftergroup command to inject a \centering before inserting a figure and then tries and restore the paragraph settings after the image is typeset.

I am trying to modify the code so that it can detect the environment that was in before the macro was expanded, i.e if the previous settings were justified then after the image is typeset the environment is restored. How do I do this?
Minimal shown below:
\documentclass{article}
\usepackage{graphicx,lipsum}
\def\agraphic{{\begin{minipage}{3cm}\par \includegraphics[width=\textwidth]{./graphics/amato}\end{minipage}\par}}
\def\testafter{{ \gdef\aword{\centering}\aftergroup\aword\aftergroup \agraphic\aftergroup\flushleft }}
\begin{document}
\lipsum[1]
\testafter
\lipsum[2]
\agraphic
\lipsum[1]
\end{document}
@currenvir? – mbork Nov 14 '11 at 23:22\leftskipand\rightskip. – mbork Nov 14 '11 at 23:23\par{\centering\includegraphics[...]{...}\par}? – egreg Nov 14 '11 at 23:24