Como colocar o número da página do cabeçalho na margem?

Como colocar o número da página do cabeçalho na margem?

Estou usando o código a seguir e não consigo descobrir como justificar o cabeçalho à esquerda na página esquerda e à direita na página direita e colocar o número da página na margem em vez de dentro da geometria definida.

\makeatletter
\def\chapapp2{Chapter}

\def\appendix{\par
 \setcounter{chapter}{0}
 \setcounter{section}{0}
 \def\chapapp2{Appendix}
 \def\@chapapp{Appendix}
 \def\thechapter{\Alph{chapter}}}

\def\ps@uheadings{\let\@mkboth\markboth
% modifications
\def\@oddhead{\protect\makebox[\textwidth][l]
        {\small\scshape\MakeUppercase{\rightmark}\hfill\thepage}}
\def\@oddfoot{}
\def\@evenfoot{}
\def\@evenhead{\protect\makebox[\textwidth][l]
        {\thepage\hfill\small\scshape\MakeUppercase{\leftmark}}}
% end of modifications
\def\chaptermark##1{\markboth {\ifnum \c@secnumdepth >\m@ne
 \chapapp2\ \thechapter. \ \fi ##1}{}}%
\def\sectionmark##1{\markright {\ifnum \c@secnumdepth >\z@
   \thesection. \ \fi ##1}}}
\makeatother

informação relacionada