# Argument in the end of an environment trick is not working

I was trying to define a new environment in which I needed to have an argument in the end code. Thanks to this post, I got that it is not possible without a trick. That is why I defined a command in the beginning containing the argument to use it in the end, but in vain... Can someone explain me why and/or fix this?

\newenvironment{newappendix}[2]%
\phantomsection%
\refstepcounter{section}%
\label{app:#2}}


Without the command \headername on the last line it works fine but I need this argument here so... What to do?

EDIT Here is a MWE (by uncommenting the last line of the end of the definition of the environment you should get an error...

\documentclass{report}

\usepackage[demo]{graphicx}
\usepackage{hyperref}
\usepackage{fancyhdr}
\pagestyle{fancy}

\setcounter{section}{0}%
\renewcommand{\thesection}{\Alph{section}}%

\newenvironment{newappendix}[2]%
\phantomsection%
\refstepcounter{section}%
\label{app:#2}}

\begin{document}

\begin{newappendix}{first}{1}
\includegraphics[width=12cm,height=15cm]{test}
\end{newappendix}

\end{document}

-
Could you create a minimal working example (MWE) rather than a code snippet so the problem is reproducible? –  Werner Jul 18 '13 at 23:12
Change \def\headername{#1} to \gdef\headername{#1}. –  Gonzalo Medina Jul 18 '13 at 23:14
@GonzaloMedina, could you please briefly explain the reason? –  Sigur Jul 18 '13 at 23:16
Isn't it easier to use \rightmark? –  egreg Jul 18 '13 at 23:17
@LudovicC. (la)tex headings are designed to use a \mark system where the page breaker informs the heading code automatically the first and last \mark on the page, marks are typically set by section headings so they can be picked up by the page head. If you set th epage head "by hand" as here it will do the wrong thing if you have multiple sections on a page or if you are unlucky and a page break happens close to a section head. –  David Carlisle Jul 18 '13 at 23:29

You should use the mark feature of LaTeX and not an environment. Here's how I would do it.

\documentclass{report}

\usepackage[demo]{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}

\usepackage{hyperref}

\renewcommand{\thesection}{\Alph{section}}

\newcommand{\newappendix}[1]{%
\clearpage % or the mark could be wrong
\refstepcounter{section}%
\markright{\thesection \ -- #1}%
}
\begin{document}

\newappendix{first}\label{app:1}
\noindent\includegraphics[width=\textwidth,height=15cm]{test}

\newappendix{second}\label{app:2}
\noindent\includegraphics[width=\textwidth,height=15cm]{test}

\newappendix{third}\label{app:3}
\noindent\includegraphics[width=\textwidth,height=15cm]{test}

\newappendix{fourth}\label{app:4}
\noindent\includegraphics[width=\textwidth,height=15cm]{test}

\end{document}

-