%%% % -*- coding: utf-8 -*-
%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% % academic-paper-abnt.sty
%%% % (Ajusta a classe ABNTeX2 ou ABNTexto)
%%% %----------------------------------------------------------
%%% % copyright: 2026 (C) by Sadao Massago
%%% % autor:
%%% %    Sadao Massago
%%% %    e-mail: sadao@ufscar.br
%%% %
%%% % Licença: LaTeX Project Public License versão 1.3c or (se for a sua escolha) qualquer versão posterior.
%%% % https://www.latex-project.org/lppl/
%%% %----------------------------------------------------------------------

\NeedsTeXFormat{LaTeX2e}[2020-10-01]  % o arquivo deve ser executado pelo LaTeX 2e versão 01/10/2020 ou posterior (devido ao AddToHoock)

% Releases
%\DeclareRelease{}{2026-10-31}{academic-paper-abnt-2026.sty} % versão anterior
\DeclareCurrentRelease{}{2026-11-01}

%%% package name
\ProvidesPackage{academic-paper-abnt}[2026-11-01 academic-paper-abnt style (require ABNTeX2 or ABNTexto as document class)]

\typeout{academic-paper-abnt style 2026-11-01 <November/2026>.}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Para evitar a tentativa de usar no modo de compatibilidade com
% LaTeX antigo (documentstyle)
%-----------------------------------------------------------------
\if@compatibility % modo de compatibilidade com LaTeX antigo?
  \PackageError{academic-paper-abnt}{Not support older compatible mode (documentstyle)}
     {Use documentclass instead of documentstyle}
  \endinput
\else
  % OK
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% requer abntex2 ou abntexto como classe de documento
%----------------------------------------------------------
\newif\if@using@abntex
\newif\if@using@abntexto
\@using@abntexfalse
\@using@abntextofalse
\@ifclassloaded{abntex2}% Using ABNTeX2?
{\@using@abntextrue}% YES (OK)
{
  \@ifclassloaded{abntexto}% Using ABNTexto?
  {\@using@abntextotrue}% YES (OK)
  { % No! Then can'not apply this package
  \PackageError{academic-paper-abnt}{Require abntex2 or abntexto as document class}
     {Use the required document class}
     %\endinput
  }
}

% from: https://www.latex-project.org/help/documentation/clsguide.pdf
% \IfClassLoadedTF{⟨class-name⟩} {⟨true code⟩} {⟨false code⟩}
\if@using@abntexto
  \IfClassAtLeastTF{abntexto}{2026-05-08}{}{%
    \PackageError{academic-paper-abnt}{abntexto is old}
      {Update the abntexto}%
  }
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Pacotes necessários
%-----------------------------------------------------------------
% para conversão em maiuscula inteligente (fórmulas matemáticas e comandos serão mantidos): O pacote textcase não é da base/required
\RequirePackage[overload]{textcase}
%opção overload executa
%\let\MakeUppercase\MakeTextUppercase
%\let\MakeLowercase\MakeTextLowercase

% Pacotes %%
\RequirePackage{graphicx} % gráficos externos

\RequirePackage{ifthen} % TeX's if can not nested. Thus, use ifthem if nesting is required (Part of header adjustment for ABNTeX)

% More macro for title
%---------------------
%\makeatletter
% comandos existentes no ABNTeX2, mas não no abntexto
\if@using@abntex % ABNTeX2
  % Novos comandos
  \newcommand{\nomeprograma}[1]{\gdef\imprimir@nome@programa{#1}}
  \newcommand{\logoesquerdo}[1]{\gdef\logo@esquerdo{#1}}
  \newcommand{\logodireito}[1]{\gdef\logo@direito{#1}}
\else % ABNTexto
  % O que já tem:
  % \title (titulo)
  % \author (autor)
  % \date (data)
  %
  % novos  
  \newcommand{\institute}[1]{\gdef\@institute{#1}}
  \newcommand{\city}[1]{\gdef\@city{#1}}
  \newcommand{\preambletext}[1]{\gdef\@preambletext{#1}}
  \providecommand{\@advisorpreffix}{}
  \providecommand{\@advisor}{}
  \newcommand{\advisor}[2][Orientador:]{%
    \gdef\@advisorpreffix{#1}%
    \gdef\@advisor{#2}%
  }
  \providecommand{\@coadvisorpreffix}{}
  \providecommand{\@coadvisor}{}
  \newcommand{\coadvisor}[2][Co-orientador:]{%
    \gdef\@coadvisorpreffix{#1}%
    \gdef\@coadvisor{#2}%
  }
  
  % O \tipotrabalho{} do ABNTeX2 é usado para diagramar ficha catalográfica.
  % Como na UFSCar, a ficha catalográfica deverá ser gerada pelo sistema de biblioteca,
  % este comando que é equivalente a \tipotrabalho{} não será usado.
  % \newcommand{\worktype}[1]{\gdef\worktype{#1}}

  % Novos comandos
  \newcommand{\programname}[1]{\gdef\@programname{#1}}
  \newcommand{\leftlogo}[1]{\gdef\@leftlogo{#1}}
  \newcommand{\rightlogo}[1]{\gdef\@rightlogo{#1}}
\fi
%\makeatother

% capa
%%%%%%
% Se ABNTeX2, altarar:
% Se ABNTexto, providenciar
\if@using@abntex

%\newcommand{\imprimircapa}{%
%  \begin{capa}%
%    \center
%    \ABNTEXchapterfont\large\imprimirautor
%
%    \vfill
%    \begin{center}
%    \ABNTEXchapterfont\bfseries\LARGE\imprimirtitulo
%    \end{center}
%    \vfill
%    
%    \large\imprimirlocal%
%
%    \large\imprimirdata
%    
%    \vspace*{1cm}
%  \end{capa}
%}

% alteração na capa:
% - todas fontes em normalfont (recomendação do ABNT 14724)
% - imprimir instituição no topo da capa
% - autor, titulo, local e data em maiúsculo
% - Em vez da capa nova, aproveita o layout do abntex2 
%\makeatletter

% \let\nome@programa@titlefontsize\ABNTEXfontereduzida

% addto não funciona, pois \imprimir@nome@programa será redefinido depois de carregar o pacote pelo comando \nomeprograma{}. Se desejar, deve colocar dentro de \imprimircapa (chamado depois de \nomeprograma{}, mas como é usado no contracapa também, colocar dentro de \imprimir capa.
%
%\addto\imprimirinstituicao{\ifx\imprimir@nome@programa\undefined \else\\ \nome@programa@titlefontsize \imprimir@nome@programa%
%\fi%
%}
%
\let\imprimircapa@original\imprimircapa
\newlength{\titletextwidth}
\renewcommand{\imprimircapa}{% inserir instituição (caso existir) no começo da capa
\bgroup%
\noindent
\setlength{\titletextwidth}{0.75\columnwidth}
%% \MakeUppercase não funciona para paragrafo
%%\def\par{\NoCaseChange{\ifvmode${}$\\\fi\endgraf}}
%\def\par{\ifvmode ${}$\\ \fi}
%\expandafter\MakeUppercase\expandafter{\imprimircapa@original}
%%
% O comando redefinido para colocar logotipo e opcionalmente o nome do programa
\abntex@ifnotempty{\imprimirinstituicao}{
\ifx\logo@esquerdo\undefined%
  \addtolength{\titletextwidth}{0.1\columnwidth}%
\else
  \begin{minipage}[c]{0.1\columnwidth}
  \noindent
  \includegraphics[width=0.98\columnwidth,height=6ex,keepaspectratio]{\logo@esquerdo}
  \end{minipage}
\fi
\ifx\logo@direito\undefined%
  \addtolength{\titletextwidth}{0.1\columnwidth}%
\fi
\hfill
\begin{minipage}[c]{\titletextwidth}%{0.75\columnwidth}
\noindent
\ABNTEXfontereduzida
\expandafter\MakeUppercase\expandafter{\imprimirinstituicao}% instituição
\ifx\imprimir@nome@programa\undefined\else% nome do programa
\\% \nome@programa@titlefontsize
\expandafter\MakeUppercase\expandafter{\imprimir@nome@programa}
\fi
%\gdef\nome@programa@titlefontsize{} % disable size
\end{minipage}
\hfill
\ifx\logo@direito\undefined\else
\begin{minipage}[c]{0.1\columnwidth}
\noindent
\begin{flushright}
\includegraphics[width=0.98\columnwidth,height=6ex,keepaspectratio]{\logo@direito}
\end{flushright}
\end{minipage}
\fi
\vfill}

% imprimir author: usar normalsize
\AddToHook{cmd/imprimirautor/before}{\normalsize}
%
% Os comandos a seguir, foram modificados para caixa, negrito, normalsize
\let\imprimirtitulo@original\imprimirtitulo
\renewcommand{\imprimirtitulo}{%
\normalsize\bfseries%
\expandafter\MakeUppercase\expandafter{\imprimirtitulo@original}
}
\let\imprimirautor@original\imprimirautor
\renewcommand{\imprimirautor}{%
\expandafter\MakeUppercase\expandafter{\imprimirautor@original}
}
\let\imprimirlocal@original\imprimirlocal
\renewcommand{\imprimirlocal}{%
\expandafter\MakeUppercase\expandafter{\imprimirlocal@original}
}
\let\imprimirdata@original\imprimirdata
\renewcommand{\imprimirdata}{%
\expandafter\MakeUppercase\expandafter{\imprimirdata@original}
}
\imprimircapa@original
\egroup}

% foha de rosto
%\let\folhaderostocontent@original\folhaderostocontent
%\renewcommand{\folhaderostocontent}{
%\bgroup%
%%\addto\imprimirinstituicao{\ifx\imprimir@nome@programa\undefined %\else\\ \imprimir@nome@programa%
%%\fi%
%%}
%\AddToHook{cmd/imprimirinstituicao/after}{\ifx\imprimir@nome@programa\undefined \else\\ \imprimir@nome@programa \fi}
%
%  \folhaderostocontent@original
%\egroup}

\renewcommand{\folhaderostocontent}{
  \begin{center}

    %\vspace*{1cm}
    {\ABNTEXchapterfont\large\imprimirautor}
	
    \vspace*{\fill}\vspace*{\fill}
    \begin{center}
      \ABNTEXchapterfont\bfseries\Large\imprimirtitulo
    \end{center}
    \vspace*{\fill}
	
    \abntex@ifnotempty{\imprimirpreambulo}{%
      \hspace{.45\textwidth}
      \begin{minipage}{.5\textwidth}
      	\SingleSpacing
         \imprimirpreambulo
       \end{minipage}%
       \vspace*{\fill}
    }%

    % remover instituição, nome do programa e orientador/coorientador
    
    %{\abntex@ifnotempty{\imprimirinstituicao}{\imprimirinstituicao\vspace*{\fill}}}

    %{\large\imprimirorientadorRotulo~\imprimirorientador\par}
    %\abntex@ifnotempty{\imprimircoorientador}{%
    %   {\large\imprimircoorientadorRotulo~\imprimircoorientador}%
    %}%
    %\vspace*{\fill}

    {\large\imprimirlocal}
    \par
    {\large\imprimirdata}
    \vspace*{1cm}

  \end{center}
}



%\makeatother


\else % \if@using@abntexto
  \newlength{\titletextwidth}  

  \newcommand{\mkcover}{%
    \begin{titlepage}
    \setlength{\titletextwidth}{0.75\columnwidth}
    
    \begin{center}
      \ifx\@leftlogo\undefined%
        \addtolength{\titletextwidth}{0.1\columnwidth}%
      \else
        \begin{minipage}[c]{0.1\columnwidth}\noindent
          \includegraphics[width=0.9\columnwidth]{\@leftlogo}
        \end{minipage}
      \fi
      \ifx\@rightlogo\undefined%
        \addtolength{\titletextwidth}{0.1\columnwidth}%
      \fi
      \hfill      
      \begin{minipage}[c]{\titletextwidth}%{0.75\columnwidth}
        \noindent
        \small
        \ifx\@institute\undefined\else% nome do       
          \expandafter\MakeUppercase\expandafter{\@institute}% instituição
        \fi
        \ifx\@programname\undefined\else% nome do programa
          \\   \expandafter\MakeUppercase\expandafter{\@programname}
\fi
      \end{minipage}
      \hfill
      \ifx\@rightlogo\undefined\else
      \begin{minipage}[c]{0.1\columnwidth}\noindent
        \begin{flushright}
          \includegraphics[width=0.9\columnwidth]{\@rightlogo}
        \end{flushright}
      \end{minipage}
    \fi
    \vfill
% Os comandos a seguir, foram modificados somente para constar na caixa alta

     \ifx\@author\undefined\else
       %\expandafter\MakeUppercase\expandafter{\large \@author}
       \expandafter\MakeUppercase\expandafter{\@author}
     \fi
     \vfill
     \ifx\@title\undefined\else
        %\expandafter\MakeUppercase\expandafter{\LARGE\bfseries \@title}
        \expandafter\MakeUppercase\expandafter{\bfseries \@title}
     \fi
     \vfill
     \ifx\@city\undefined\else
       \expandafter\MakeUppercase\expandafter{\normalsize \@city}
     \fi
     \par
     \ifx\@date\undefined\else
       \expandafter\MakeUppercase\expandafter{\normalsize \@date}
     \fi
    
    \vspace*{1cm}
    \end{center}  
    \end{titlepage}
  }
  
  % contra capa
  \newcommand{\mkcoverpage}{%
    \begin{center}
     {
     \large
     \ifx\@author\undefined\else
       \@author
     \fi
     }
     
     \vspace*{\fill}\vspace*{\fill}
     
     {\Large\bfseries
     \ifx\@title\undefined\else
        \@title
     \fi
     }
            
     \vspace*{\fill}
     
     \ifx\@preambletext\undefined\else
       \hspace{.45\textwidth}
        \begin{minipage}{.5\textwidth}
      	  \noindent % sem indentação
      	  \singlesp % espaçamento simpoles, usando o comando de ABNTexto
          \@preambletext
        \end{minipage}%
        \vspace*{\fill}
     \fi
   
%    reemovendo instituição, nome do programa e orientador/coorientador   

%    \ifx\@institute\undefined\else% nome do       
%       \@institute% instituição
%    \fi
%    \par
%    \ifx\@programname\undefined\else% nome do programa
%      \@programname
%    \fi
%    
%    \vspace*{\fill}
%    
%    {\large
%    \ifx\@advisor\undefined\else% nome do       
%       \@advisorpreffix{} \@advisor% 
%    \fi
%    \par
%    \ifx\@coadvisor\undefined\else% nome do       
%       \@coadvisorpreffix{} \@coadvisor% 
%    \fi
%    }
%    
%    \vspace*{\fill}

     {\large
     \ifx\@city\undefined\else
       \@city
     \fi
     \par
     \ifx\@date\undefined\else
       \@date
     \fi
     }
    
    \vspace*{1cm}

      
    \end{center}
  }
    
\fi

% \usepackage[english,brazilian]{babel}

\if@using@abntexto
  \usechapters% ativar o uso de \chapter{}
% Na bibliografia, glossário, índice remissivo, etc, continua como section. Requer ajustes
  % abntexto 2025-07-17 usa newcounter
%  
%  % abntexto define o contador \c@chapter usando \newcount do TeX.
%  % \newcount\c@chapter% não usado no abntexto (logo, pode ser removido no futuro)
%  
%  % Para que a subordinação de outros contadores funcionem devidamente (como feito pelo \numberwithin{}{}, \newtheorem{}{}[] e \newcounter{}[]), precisa ter \c@<countador> (contador principal) e \cl@<contador> (lista de comandos para resetar os contadores subordinados). Assim, deve ter o seguinte comando
%
%  % Para capítulo
%  \@ifundefined{c@chapter}{\newcount \c@chapter}{}% contador principal
%  \global\let\cl@chapter\@empty% lista de aplicações de \@elt nos contadores subordinados (ao executar, aplicará \@elt em cada um dos contadores subordinados)
%
%  % Para part
%  %\@ifundefined{c@part}{\newcount \c@part}{}% contador principal
%  %\global\let\cl@part\@empty%  
%  % para que na recontagem, resetar os contadores subordinados
%
%  % macro para aplicar \@stlelt em vez de \@elt
%  % No stepcounter{}, está guardando/restaurando o \@elt original pelo agrupamento apenas, mas por algum motivo, não funciona aqui e precisa fazer explicitamente. Senão, causa o erro de falta de \endcsname quando figuras flutuantes ficam na página separada (provavelmente, usará o \@elt para este caso).
%  
%  \def\@stpelt@on@cl#1{
%     \begingroup% agrupando para que mudanças seja local.
%      \let\@elt@original\@elt% copia do original
%      \let\@elt\@stpelt % \@elt será o \@stpelt
%      \csname cl@#1\endcsname % aplica o \@elt em cada contador
%      \let\@elt\@elt@original% restaura o \@elt original
%    \endgroup
%  }
%  
%  % Se usar \addto, deve carregar o babel
%  % \addto\recountchapter{\@stpelt{chapter}}
%  %
%  %\let\recountpart@original\recountpart % parte
%  %\def\recountpart{\recountpart@original\@stpelt@on@cl{part}}
%
%  %  \let\recountchapter@original\recountchapter % capítulo
%  %\def\recountchapter{\recountchapter@original\@stpelt@on@cl{chapter}}
%  % \let\recountsection@original\recountsection % seção
%  % \def\recountsection{\recountsection@original\@stpelt@on@cl{section}}
%  %\let\recountsubsection@original\recountsubsection % subseção
%  %\def\recountsubsection{\recountsubsection@original\@stpelt@on@cl{subsection}}
%  %\let\recountsubsubsection@original\recountsubsubsection % subsubseção
%  %\def\recountsubsubsection{\recountsubsubsection@original\@stpelt@on@cl{subsubsection}}
%  %\let\recountparagraph@original\recountparagraph % paragraph
%  %\def\recountparagraph{\recountparagraph@original\@stpelt@on@cl{paragraph}}
%
%  % \AddToHook{cmd/recountpart/after}{\@stpelt@on@cl{part}}
%  \AddToHook{cmd/recountchapter/after}{\@stpelt@on@cl{chapter}}
%  \AddToHook{cmd/recountsection/after}{\@stpelt@on@cl{section}}
%  \AddToHook{cmd/recountsubsection/after}{\@stpelt@on@cl{subsection}}
%  \AddToHook{cmd/recountsubsubsection/after}{\@stpelt@on@cl{subsubsection}}
%  % \AddToHook{cmd/recountparagraph/after}{\@stpelt@on@cl{paragraph}}

  % capítulo versão * para pre textual

  % Para trabalhos academicos
  % \let\chapter@original\chapter% copiando o original
  \let\chapter@nostar\chapter% copiando o original
  \def\chapter{\@ifstar\chapter@star\chapter@nostar}
  %\def\chapter@nostar#1{\chapter@original{#1}\@stpelt{chapter}}% sem *
  % \def\chapter@nostar#1{\chapter@original{#1}}% sem *
  \def\chapter@star#1{% com *
    %\clearpage\vspace*{\abovechapter}
    %\noindent{\Huge\bfseries #1}%
    %\par\vskip\belowchapter
    %\clearpage
    % \nonum\notoc\chapter@original{\centering #1}
    \clearpage
    \nonum\notoc\chapter@nostar{\centering #1}
  }
 
\fi

\if@using@abntex
% para \bibname aparecer maiusculo no sumário
%\makeatletter
% truque de https://github.com/abntex/abntex2/issues/200
% ajustado
\AtBeginDocument{
  \@ifpackageloaded{biblatex}{
    \defbibheading{bibliography}[\refname]{%
        \chapter*{#1}%
        \if@twoside
        \markboth{\abx@MakeMarkcase{#1}}{\abx@MakeMarkcase{#1}}%
        \else
        \markright{\abx@MakeMarkcase{#1}}%
        \fi
        \ifmemoirbibintoc
        {\phantomsection
        \addcontentsline{toc}{chapter}{\MakeUppercase{#1}}}
        {}}
  }{}
}
\else %\if@using@abntexto
\AtBeginDocument{
  \@ifpackageloaded{biblatex}{
    \defbibheading{bibliography}[\refname]{%
        \begingroup
          %\def\hookprintchapter##1{\centering ##1} % not work?
          % ABNTexto desativa a centralização após iniciar o textual
          % centralizando manualmente
          \chapter*{\centering #1}%
          % espaço antes do \appendix no ABNTexto é pequeno.
          % Inserir espaço extra após referẽncias para compendar
          \addtocontents{toc}{\bigskip}
        \endgroup
        \if@twoside
        \markboth{\MakeUppercase{#1}}{\MakeUppercase{#1}}%
        \else
        \markright{\MakeUppercase{#1}}%
        \fi
        %\ifmemoirbibintoc
        %{\phantomsection
        %\addcontentsline{toc}{chapter}{\MakeTextuppercase{#1}}}
        %{}
        }%\defbibheading
  }{}
}

\fi

\if@using@abntexto

% indice remissivo

%\AtBeginDocument{
  %\@ifpackageloaded{makeidx}{
   % sem usar AddToHook 
   % \let\@printindex@original\printindex  
   % \def\printindex{
   %   \begingroup
   %     \let\sectionoriginal\section
   %     \let\section\chapter
   %     \@printindex@original
   %     \let\section\sectionoriginal
   %   \endgroup
   % }   
   % usando AddToHook
   % \AddToHook{cmd/beginprintindex/before}{
   %   \let\@section@original\section
   %   \let\section\chapter
   % }
   % \AddToHook{cmd/endprintindex/after}{
   %   \let\section\@section@original
   % }    
  %} % \@ifpackageloaded{makeidx}{ 
%} % \AtBeginDocument{

  % Índice remissivo
  \AddToHook{env/theindex/begin}{
    %\let\@section@original\section
    %\let\section\chapter
    \begin{corrprint}
  }
  \AddToHook{env/theindex/end}{
    %\let\section\@section@original
    \end{corrprint}
  }
  
  % referências bibliográficas (bibtex)
  \AddToHook{env/thebibliography/begin}{
    %\let\@section@original\section
    %\let\section\chapter
    \begin{corrprint}
  }
  \AddToHook{env/thebibliography/end}{
    %\let\section\@section@original
    \end{corrprint}
  }

  % referências bibliográficas (biblatex)
  \AddToHook{cmd/printbibliography/before}{
    %\let\@section@original\section
    %\let\section\chapter
    \begin{corrprint}
  }
  \AddToHook{cmd/printbibliography/after}{
    %\let\section\@section@original
    \end{corrprint}
  }

  % Glossário com pacote glossaries
  \AtBeginDocument{
    \@ifpackageloaded{glossaries}{
      \AddToHook{cmd/printglossary/before}{
        %\let\@section@original\section
        %\let\section\chapter
        \begin{corrprint}
      }
      \AddToHook{cmd/printglossary/after}{
        %\let\section\@section@original
        \end{corrprint}
      }    
    }{} %\@ifpackageloaded
  } %\AtBeginDocument
  
  % Glossário com pacote acro
  \AtBeginDocument{
    \@ifpackageloaded{acro}{
      \AddToHook{cmd/printacronyms/before}{
        %\let\@section@original\section
        %\let\section\chapter
        \begin{corrprint}
      }
      \AddToHook{cmd/printacronyms/after}{
        %\let\section\@section@original
        \end{corrprint}
      }    
    }{} %\@ifpackageloaded
  } %\AtBeginDocument

\fi % \if@using@abntexto

% Desativando alguns comandos no bookmarks de PDF 
% \\ e \and já esta desabilitado para ABNTeX2, mas não para ABNTexto
\AtBeginDocument{%
  \@ifpackageloaded{hyperref}{%
    \pdfstringdefDisableCommands{\let\MakeUppercase\relax}% desabilitando
    \if@using@abntexto
      \pdfstringdefDisableCommands{\def\\{, } \def\and{; }}
    \fi
  }{}
}
%\makeatother

% No ABNTeX2, aparece cabeçalho com paginação sobre o sumário, quando for de mais uma página. Deve ser removido
% Traçar linha horizontal na primeira página do capítulo também

% \ifthenelse é fragil (não pode usar dentro de section{}, etc.
% Então está usando aqui e dentro de \markboth{}{}, está usando o \if
% (\if não pode ser usado dentro do outro \if, \ifthenelse{}{} pode)
\ifthenelse{\boolean{@using@abntex}}{%
  % Ajustando o cabeçalho
  %
  % linha orizontal na primeira página do capitulo também
  \makeheadrule{abntchapfirst}{\textwidth}{\normalrulethickness}
  % copiando o estilo
  \let\ps@abntheadingsoriginal\ps@abntheadings % cópia do original
  % Quando chamar \pretextual (ou \frontmatter), configurar como empty
  \AddToHook{cmd/pretextual/before}
  {\clearpage\aliaspagestyle{abntheadings}{empty}}
  % Quando chamar \textual (ou \mainmatter), restaurar o estilo
  \AddToHook{cmd/textual/before}
  {\clearpage\aliaspagestyle{abntheadings}{abntheadingsoriginal}}
  %
  % ajustando o \chaptermark{} e desabilitando o \sectionmark{}
  %\AddToHook{fancyhdr/after}{%
  \renewcommand{\chaptermark}[1]{% remover string 'Capítulo'
    \markboth{\if@mainmatter\thechapter. \fi #1}{\if@mainmatter\thechapter. \fi #1}}  
  % Se dois lados, reativar sectionmark 
  \if@twoside%
    \renewcommand{\sectionmark}[1]{%
      \markright{\if@mainmatter\thesection. \fi#1}}%
  \fi
  %
  % ficha catalográfica não deve ser contada ABNT NBR 14724 (2024)
  % caso de somente anverso (frente) parece ser contada
  \if@twoside
    \AddToHook{env/fichacatalografica/after}{\addtocounter{page}{-1}} % retornar uma página
  \fi  
}{} %\ifthenelse{\booelan{@using@abntex}}{

% Referencias aparecendo como biliografia. Corrigindo
% https://github.com/abntex/abntex2/issues/200
\ifthenelse{\boolean{@using@abntex}}{%
  \AtBeginDocument{
    \@ifpackageloaded{biblatex}{
       \ifthenelse{\boolean{ABNTEXupperchapter}}{%
         \DefineBibliographyStrings{brazilian}{%
           bibliography = {\MakeUppercase{Referências}},
         }
       }{%
         \DefineBibliographyStrings{brazilian}{%
           bibliography = {Referências},
         }
       }
       %\DefineBibliographyStrings{brazilian}{% 
         % not works
         % bibliography = {\makeatletter\ABNTEXchapterupperifneeded{Referências}\makeatother},              
         % works
         % bibliography = {\MakeUppercase{Referências}},
        %\newcommand{\ABNTEXchapterupperifneeded}[1]{\ifthenelse{\boolean{ABNTEXupperchapter}}{\MakeTextUppercase{#1}}{#1}}
       %}
    }
    % not work
    %\defbibliographyheading{bibintoc}[\refname]{%
    %  \chapter*{#1}%
    %  \addcontentsline{toc}{chapter}{#1}%
    %}
    %\defbibheading{bibintoc}[REFERÊNCIAS]{%
    %    \chapter*{#1}%
    %    \addcontentsline{toc}{chapter}{#1}%
    %    \if@twoside\markboth{#1}{#1}\else\markthis{#1}\fi%
    %}
  }
  %\renewcommand{\refname}{Referências}% artigos
}{}

%% ajustando o tamanho das fontes dos titulos de seccionamento no ABNTeX2
% NBR 14724 (todos devem ser de mesmo tamanho)

\ifthenelse{\boolean{@using@abntex}}{%
  \setboolean{ABNTEXupperchapter}{true} % caixa alta
  \setboolean{ABNTEXuppersection}{true} % caixa alt
  \setboolean{ABNTEXuppersubsection}{false}
  \setboolean{ABNTEXuppersubsubsection}{false}
  \setboolean{ABNTEXuppersubsubsubsection}{false}


  % \setlength{\beforechapskip}{0pt} % antes
  % \setlength{\midchapskip}{0pt} % entre número de titulo
  % reduzindo o espaço após titulo do capítulo
  \setlength{\afterchapskip}{\baselineskip}
  % Seções em diante, pode ser ajustado com set também
  %\setlength{\beforesecskip}{\baselineskip} % antes
  % \setlength{\aftersecskip}{\baselineskip} % depois
  % seção
  \setbeforesecskip{\baselineskip}
  \setaftersecskip{\baselineskip}
  % subseção
  \setbeforesubsecskip{\baselineskip}
  \setaftersubsecskip{\baselineskip}
  % sub sub seção
  \setbeforesubsubsecskip{\baselineskip}
  \setaftersubsubsecskip{\baselineskip}
  % sub sub sub seção do ABNTeX2 é um atalho para paragraph
  \setbeforeparaskip{\baselineskip}
  \setafterparaskip{\baselineskip}

  % capítulo: caixa alta e negrito  
  \renewcommand{\ABNTEXchapterfont}{\sffamily\bfseries}
  \renewcommand{\ABNTEXchapterfontsize}{\normalsize}
  % seção: caixa alta sem negrito
  \renewcommand{\ABNTEXchapterfont}{\sffamily}
  \renewcommand{\ABNTEXsectionfontsize}{\normalsize}
  % subseção: caixa baixa em negrito
  \renewcommand{\ABNTEXsubsectionfont}{\sffamily\bfseries}
  \renewcommand{\ABNTEXsubsectionfontsize}{\normalsize}
  % subsubseção: normal
  \renewcommand{\ABNTEXsubsubsectionfont}{\normalfont}
  % subsubsubseção (atalho para paragraph): itálico
  \renewcommand{\ABNTEXsubsubsubsectionfont}{\itshape}
}{}

\ifthenelse{\boolean{@using@abntexto}}{%
  \def\belowchapter{\baselineskip}

  %\def\printchapter#1{\hookchapter \trytextual
  %  \leavevmode \vskip\abovechapter\relax
  %  \noindent\targetchapter{#1}%
  %  \begingroup
  %      \raggedright\huge\bfseries
  %      \ifnonum \else Capítulo \thechapter \vskip20pt \fi
  %      \Huge\bfseries \hookprintchapter{#1\par}%
  %  \endgroup
  %  \chaptermark{#1}%
  %  \nobreak \bottitle{\vskip\belowchapter}%
  % }
    
  \def\printchapter#1{\hookchapter \trytextual
    \leavevmode \vskip\abovechapter\relax%
    \noindent\targetchapter{\MakeTextUppercase{#1}}%
    \begingroup
        \raggedright\bfseries
        \ifnonum \else \thechapter\quad\fi
        \hookprintchapter{\MakeTextUppercase{#1}\par}%
    \endgroup
    \chaptermark{\MakeTextUppercase{#1}}%
    \nobreak \bottitle{\vskip\belowchapter}% 
  }%
  
  %\def\printsection#1{\hooksection \trytextual
  %  \par\toptitle{\penalty-300}{\vskip\abovesection}%
  %  \noindent\targetsection{#1}%
  %  \ifnonum
  %      {\centering\sectionfont{\hookprintsection{#1\nbpar}}}%
  %  \else
  %      {\sectionfont{\hangfrom{\thesection\quad}#1\nbpar}}\sectionmark{#1}%
  %  \fi
  %  \nobreak \bottitle{\vskip\belowsection}%
  %}
  
  \def\printsection#1{\hooksection \trytextual
    \par\toptitle{\penalty-300}{\vskip\abovesection}%
    \noindent\targetsection{\MakeTextUppercase{#1}}%
    \ifnonum
        {\centering\sectionfont{\hookprintsection{\MakeTextUppercase{#1}\nbpar}}}%
    \else
        {\sectionfont{\hangfrom{\thesection\quad}\MakeTextUppercase{#1}\nbpar}}\sectionmark{\MakeTextUppercase{#1}}%
    \fi
    \nobreak \bottitle{\vskip\belowsection}%
  }  
}{}

% refazendo dedicatoria e epigrafe conforme recomendação do ABNT 14724
\ifthenelse{\boolean{@using@abntex}}{%
  %\newenvironment{dedicatoria}[1][]{%
  %   \ifthenelse{\equal{#1}{}}{%
  %    \PRIVATEbookmarkthis{\dedicatorianame}
  %    }{\pretextualchapter{#1}}
  %  }{\PRIVATEclearpageifneeded}
  \renewenvironment{dedicatoria}{%
    \PRIVATEbookmarkthis{\dedicatorianame}
    ~\vfill\hfill\begin{minipage}{0.5\textwidth}
  }{%
    \end{minipage}
    \PRIVATEclearpageifneeded
  }

  % Epigrafe
  % \newenvironment{epigrafe}[1][]{%
  %   \ifthenelse{\equal{#1}{}}{%
  %    \PRIVATEbookmarkthis{\epigraphname}
  %    }{\pretextualchapter{#1}}
  % }{\PRIVATEclearpageifneeded}
% 

  \renewenvironment{epigrafe}{%
    \PRIVATEbookmarkthis{\epigraphname}
    ~\vfill\hfill\begin{minipage}{0.5\textwidth}
  }{%
    \end{minipage}
    \PRIVATEclearpageifneeded
  }

}{}
% -

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Ajustando as penalidades...
% CONTROLE DA LINHA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Overfull \hbox (xx pt too wide) -> a linha ultrapassou xx pontos
% Underfull \hbox (badness xx) -> muito espaço entre palavras, na linha.
% xx e a pontuacao de como e ruim, de 0 a 10000.
%
% Para evitar o Overflow \hbox, podera usar \sloppy
% quando utiliza \sloppy, permite a quebra de linha, mesmo que ocorra
% underflow \hbox (muito espaço entre palavras)
% Pra permitir quebra de linha com bastante espaço entre linhas, somente num trecho, poderá usar o ambiente sloppypar:
% \begin{sloppypar}  \end{sloppypar}
%
% O \sloppy e desativado por comando \fussy
%
%========================================================================
% redefinição de \sloppy
% Poderá voltar pra valor original de \sloppy, usando \fussy
%------------------------------------------------------------------------

\def\sloppy{\tolerance=9999 \hfuzz=.5pt \vfuzz=.5pt}
% \sloppy % já aplica

% ambiente sloppypar será ajustado automaticamente, quando ajusta
% o \sloppy
%
% Se não precisar do formato justificado, poderá usar o ambiente quote
% e o comando \raggedrigth da forma
% \begin{quote}\raggedright ... \end{quote}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HIFENIZAÇÃO
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Poderá configurar a hifenização das palavras fora de regras,
% usando \hyphenation no preãmbulo, tais como
% \hyphenation{hi-fe-niza-ção au-xi-liar tes-te}
% Para criar hifenizacao temporária dentro do texto, 
% mesmo que tenha desativado a hifenização,
% coloca-se a palavra entre chaves e separa por \-.
% Ex.: {re\-vi\-go\-ra\-men\-to} {com\-ple\-ta\-men\-te}
%========================================================================
% Para impedir a hifenização,
% coloque alta penalidade na hifenização

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PENALIZAÇÂO
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% alterando a penalização da corte de linha antes (ou depois)
%---------------------------------------------------------------
% configuração original
%
% \linepenalty=10
% \hyphenpenalty=50
% \exhyphenpenalty=50
% \binoppenalty=700
% \relpenalty=500
% \clubpenalty=150
% \widowpenalty=150
% \displaywidowpenalty=50
% \brokenpenalty=100
% \predisplaypenalty=10000
%-------------------------------------------------------
% alterando as penalidades (para corte de linhas em...)
\hyphenpenalty=5000 % hifenização
\exhyphenpenalty=500 % palavras com hifen
\binoppenalty=3000 % operador binario (+, - , etc)
\relpenalty=2000 % operador relacional ( = \cong \ne, ...)
\clubpenalty=1000 % ???
\brokenpenalty=1000 % ???

% ---
% Posiciona figuras e tabelas no topo da página quando
% adicionadas sozinhas em uma página em branco.
% Ver https://github.com/abntex/abntex2/issues/170
%\makeatletter
\if@using@abntex
  \setlength{\@fptop}{5pt} % Set distance from top of page to first float
\fi
%\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Como não tem declaração de opções, não é 
% necessário colocar \ProcessOptions
% no final dde processamento das opções
%-------------------------------------------------

% \ProcessOptions
% fim: ppgece-ufscar.sty

