CREATE OR REPLACE PROCEDURE ARQUIVO_DECLAN(
   P_NRSEQARQMAG  IN  NOTAFISCAL.NRLANCTONF%TYPE,
   P_STIDREGISTRO IN  INSCRESTAD.CDINSCESTA%TYPE,
   P_CDIMPOSTO    IN  IMPOSTONF.CDIMPOSTO%TYPE,
   P_CDEMPRESA    IN  NOTAFISCAL.CDEMPRESA%TYPE,
   P_CDINSCESTA   IN  INSCRESTAD.CDINSCESTA%TYPE,
   P_CDLIVROMAG   IN  CFOPLIVROMAG.CDLIVROMAG%TYPE,
   P_DTANO        IN  NOTAFISCAL.NRLANCTONF%TYPE,
   P_VERSAO       IN  NOTAFISCAL.NRLANCTONF%TYPE,
   P_DTENCER      IN  NOTAFISCAL.DTEMISSAO%TYPE,
   P_DTINICIO     IN  NOTAFISCAL.DTEMISSAO%TYPE,
   P_RETIFICA     IN  NOTAFISCAL.NRLANCTONF%TYPE,
   P_CONTRIBU     IN  NOTAFISCAL.NRLANCTONF%TYPE)

AS
   V_DTINICIAL      DATE;
   V_DTFINAL        DATE;

   V_CONT_LINHA     NUMBER;
   V_DADOS_0001     VARCHAR2(4000);
   V_DADOS_0100     VARCHAR2(4000);
   V_DADOS_0200     VARCHAR2(4000);
   V_DADOS_0300     VARCHAR2(4000);
   V_DADOS_0400     VARCHAR2(4000);
   V_DADOS_0500     VARCHAR2(4000);
   V_DADOS_9999     VARCHAR2(4000);

   V_TPPESSOA       VARCHAR2(01);
   V_INSCCONTR      VARCHAR2(20);
   V_RAZSOCCONTR    VARCHAR2(80);
   V_EMAILCONTR     VARCHAR2(100);
   V_NMREPRE        VARCHAR2(64);
   V_TELCONTR       VARCHAR2(25);
   V_FAXCONTR       VARCHAR2(25);
   V_NMCONTADOR     VARCHAR2(64);
   V_TELCONTADOR    VARCHAR2(25);
   V_DTENCER        DATE;

   V_LOCALCONTRIB   VARCHAR2(08);

   V_VRESTADOENT    NUMBER;
   V_FORA_ESTADOENT NUMBER;
   V_EXTERIORENT    NUMBER;
   V_TOTENT         NUMBER;
   V_VRESTADOSAI    NUMBER;
   V_FORA_ESTADOSAI NUMBER;
   V_EXTERIORSAI    NUMBER;
   V_TOTSAI         NUMBER;

   V_MERCESTENT     NUMBER;
   V_MERCFORAESTENT NUMBER;
   V_MERCEXTENT     NUMBER;
   V_MERCTOTENT     NUMBER;
   V_MERCESTSAI     NUMBER;
   V_MERCFORAESTSAI NUMBER;
   V_MERCEXTSAI     NUMBER;
   V_MERCTOTSAI     NUMBER;

   V_CDIMPOSTRIB    VARCHAR2(02);
   V_VRSTSAIDA      NUMBER;
   V_VRSTENTRADA    NUMBER;
   V_CODAJUSTE      VARCHAR2(05);
   V_VRAJUSTE       NUMBER;
   V_DTESTOQUE      DATE;
   V_VRTOTAJUSTE    NUMBER;
   V_VRBCIPIS       NUMBER;
   V_VRIMPIPIS      NUMBER;
   V_VRBCIPIE       NUMBER;
   V_ESTFIM           DATE;
   V_ESTINI           DATE;
   V_VRTOTDISTRIB   NUMBER;

   V_CONT_MES       NUMBER;
   V_VRRECBRESTA    NUMBER;
   V_VRRECBREMPR    NUMBER;

   V_TOTAL          NUMBER;

BEGIN
   V_CONT_LINHA   := 0;
   V_CONT_MES     := 0;
   V_VRTOTAJUSTE  := 0;
   V_VRTOTDISTRIB := 0;

   IF (P_DTINICIO IS NOT NULL) AND (TO_CHAR(P_DTINICIO,'YYYY') = P_DTANO) THEN
      V_DTINICIAL := P_DTINICIO;
   ELSE
      V_DTINICIAL := TO_DATE('01/01/'||(P_DTANO));
   END IF;

   IF P_CONTRIBU = 'S' THEN
      V_DTFINAL := P_DTENCER;
   ELSE
      V_DTFINAL := TO_DATE('31/12/'||P_DTANO);
   END IF;

   -- Arquivo de cabecalho "0001".

   V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
   V_DADOS_0001 := '0001'                              ||
                   TO_CHAR (SYSDATE, 'YYYYMMDDHHMISS') ||
                   'N'                                 ||
                   RPAD(NVL(P_VERSAO, ' '), 10, ' ')   ||
                   RPAD(' ', 326, ' ')                 ||
                   LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0001, P_NRSEQARQMAG);

   -- Registro "0100".

   BEGIN
      SELECT I.IDTPIJURIEST, I.NRINSJURIEST, I.NMREPRINSEST,  I.NRTELEIEST,
             I.NRFAXIEST, E.NMRAZSOCEMPR, E.DSEMAILEMPRESA
        INTO V_TPPESSOA, V_INSCCONTR, V_NMREPRE, V_TELCONTR,
             V_FAXCONTR, V_RAZSOCCONTR, V_EMAILCONTR
        FROM INSCRESTAD I, EMPRESA E
       WHERE I.CDEMPRESA  = P_CDEMPRESA
         AND I.CDINSCESTA = P_CDINSCESTA
         AND I.CDEMPRESA  = E.CDEMPRESA;
   EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_TPPESSOA    := NULL;
           V_INSCCONTR   := NULL;
           V_NMREPRE     := NULL;
           V_TELCONTR    := NULL;
           V_FAXCONTR    := NULL;
           V_RAZSOCCONTR := NULL;
           V_EMAILCONTR  := NULL;
   END;

   BEGIN
      SELECT M.CDMUNIEXPO
        INTO V_LOCALCONTRIB
        FROM INSCRESTAD I, MUNICIPIO M
       WHERE I.CDEMPRESA   = P_CDEMPRESA  AND
             I.CDINSCESTA  = P_CDINSCESTA AND
             I.CDPAIS      = M.CDPAIS     AND
             I.SGESTADO    = M.SGESTADO   AND
             I.CDMUNICIPIO = M.CDMUNICIPIO;
   EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_LOCALCONTRIB := NULL;
   END;

   BEGIN
      SELECT NMCONTADOR, NRTELCONTATO
        INTO V_NMCONTADOR, V_TELCONTADOR
        FROM CONTADOR C, INSCRESTAD I
       WHERE I.CDEMPRESA   = P_CDEMPRESA
         AND I.CDINSCESTA  = P_CDINSCESTA
         AND I.CDCONTADOR2 = C.CDCONTADOR2;
   EXCEPTION
        WHEN NO_DATA_FOUND THEN
           V_NMCONTADOR    := NULL;
           V_TELCONTADOR   := NULL;
   END;

   IF P_CONTRIBU = 'S' THEN
      V_DTENCER := P_DTENCER;
   ELSE
      V_DTENCER := TO_DATE('');
   END IF;

   V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
   V_DADOS_0100 := '0100'                                    ||
                   '000000000000001'                         ||
                   LPAD(NVL(P_CDINSCESTA, '0'), 8, '0')      ||
                   LPAD(NVL(P_DTANO, '0'), 4, '0')           ||
                   NVL(P_RETIFICA, 'N')                      ||
                   'N'                                       ||
                   NVL(V_TPPESSOA,'J')                       ||
                   LPAD(V_INSCCONTR,14,'0')                  ||
                   RPAD(SUBSTR(NVL(V_RAZSOCCONTR,' '),1,64), 64, ' ') ||
                   RPAD(SUBSTR(NVL(V_EMAILCONTR,' '), 1,40), 40, ' ') ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_TELCONTR,'(',''),')',''),'-',''),' ',''),'.',''),1,2 ),' '), 4, ' ')    ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_TELCONTR,'(',''),')',''),'-',''),' ',''),'.',''),3,10),' '), 8, ' ')    ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_FAXCONTR,'(',''),')',''),'-',''),' ',''),'.',''),1,2 ),' '), 4, ' ')    ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_FAXCONTR,'(',''),')',''),'-',''),' ',''),'.',''),3,10),' '), 8, ' ')    ||
                   LPAD(NVL(V_LOCALCONTRIB,'0'), 8, '0')     ||
                   RPAD(NVL(V_NMREPRE, ' '), 64, ' ')        ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_TELCONTR,'(',''),')',''),'-',''),' ',''),'.',''),1,2 ),' '), 4, ' ')    ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_TELCONTR,'(',''),')',''),'-',''),' ',''),'.',''),3,10),' '), 8, ' ')    ||
                   RPAD(NVL(V_NMCONTADOR, ' '), 64, ' ')     ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_TELCONTADOR,'(',''),')',''),'-',''),' ',''),'.',''),1,2 ),' '), 4, ' ') ||
                   RPAD(NVL(SUBSTR(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(V_TELCONTADOR,'(',''),')',''),'-',''),' ',''),'.',''),3,10),' '), 8, ' ') ||
                   NVL(P_CONTRIBU, 'N')                      ||
                   NVL(TO_CHAR(V_DTENCER,'YYYYMMDDHHMISS'),'00000000000000') ||
                   SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 8, 4) ||
                   LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0100, P_NRSEQARQMAG);

   --Registro "0200".

   IF SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 1, 1) = 'S' THEN
      BEGIN
         SELECT SUM(NF.VRESTADO) VRESTADOENT, SUM(NF.FORA_ESTADO) FORA_ESTADOENT, SUM(NF.EXTERIOR) EXTERIORENT
           INTO V_VRESTADOENT, V_FORA_ESTADOENT, V_EXTERIORENT
           FROM(SELECT SUM(DECODE(SUBSTR(CDFISCOPERNF,1,1),'1',ROUND(VRCONTABILNF,2),0)) AS VRESTADO,
                       SUM(DECODE(SUBSTR(CDFISCOPERNF,1,1),'2',ROUND(VRCONTABILNF,2),0)) AS FORA_ESTADO,
                       SUM(DECODE(SUBSTR(CDFISCOPERNF,1,1),'3',ROUND(VRCONTABILNF,2),0)) AS EXTERIOR
                  FROM IMPOSTONF I, NOTAFISCAL N, IMPOSTO IM
                 WHERE IM.CDIMPOSTONFE = P_CDIMPOSTO
                   AND IM.CDIMPOSTO    = I.CDIMPOSTO
                   AND IDENTRSAIDOP    = 'E'
                   AND DTENTRSAID BETWEEN V_DTINICIAL AND V_DTFINAL
                   AND IDSTATUS IN ('A','E')
                   AND I.NRSEQUMAPAPU IS NOT NULL
                   AND I.CDFILIAL   = N.CDFILIAL
                   AND I.NRLANCTONF = N.NRLANCTONF
                   AND N.CDEMPRESA  = P_CDEMPRESA
                   AND N.CDINSCESTA = P_CDINSCESTA
                   AND ((I.IDIMPOSTONF <> '3') OR (I.IDIMPOSTONF IS NULL))) NF;
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRESTADOENT    := NULL;
              V_FORA_ESTADOENT := NULL;
              V_EXTERIORENT    := NULL;
      END;

      BEGIN
         SELECT SUM(NF.VRESTADOSAI) VRESTADOSAI, SUM(NF.FORA_ESTADOSAI) FORA_ESTADOSAI, SUM(NF.EXTERIORSAI) EXTERIORSAI
           INTO V_VRESTADOSAI, V_FORA_ESTADOSAI, V_EXTERIORSAI
           FROM(SELECT SUM(DECODE(SUBSTR(CDFISCOPERNF,1,1),'5',ROUND(VRCONTABILNF,2),0)) AS VRESTADOSAI,
                       SUM(DECODE(SUBSTR(CDFISCOPERNF,1,1),'6',ROUND(VRCONTABILNF,2),0)) AS FORA_ESTADOSAI,
                       SUM(DECODE(SUBSTR(CDFISCOPERNF,1,1),'7',ROUND(VRCONTABILNF,2),0)) AS EXTERIORSAI
                  FROM IMPOSTONF I, NOTAFISCAL N, IMPOSTO IM, CFOPPADRAO P
                 WHERE IM.CDIMPOSTONFE = P_CDIMPOSTO
                   AND IM.CDIMPOSTO    = I.CDIMPOSTO
                   AND IDENTRSAIDOP    = 'S'
                   AND DTEMISSAO BETWEEN V_DTINICIAL AND V_DTFINAL
                   AND IDSTATUS IN ('A','E')
                   AND I.NRSEQUMAPAPU IS NOT NULL
                   AND I.CDFILIAL   = N.CDFILIAL
                   AND I.NRLANCTONF = N.NRLANCTONF
                   AND I.CDFISCOPERNF = P.CDCFOPPADRAO
                   AND NVL(P.IDTIPOCFOP,'T') <> 'D'
                   AND N.CDEMPRESA  = P_CDEMPRESA
                   AND N.CDINSCESTA = P_CDINSCESTA) NF;
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRESTADOSAI    := NULL;
              V_FORA_ESTADOSAI := NULL;
              V_EXTERIORSAI    := NULL;
      END;
   ELSE
      V_VRESTADOENT    := 0;
      V_FORA_ESTADOENT := 0;
      V_EXTERIORENT    := 0;
      V_VRESTADOSAI    := 0;
      V_FORA_ESTADOSAI := 0;
      V_EXTERIORSAI    := 0;
   END IF;

   V_TOTENT := NVL(V_VRESTADOENT,0) + NVL(V_FORA_ESTADOENT,0) + NVL(V_EXTERIORENT,0);
   V_TOTSAI := NVL(V_VRESTADOSAI,0) + NVL(V_FORA_ESTADOSAI,0) + NVL(V_EXTERIORSAI,0);

   /*O Resumo de Mercadorias so deve ser informado quando houver no ano-base, simultaneamente,
     as atividades de operacao com mercadoria e de prestacao de servico (com incidencia do ICMS)*/
   IF SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 1, 1)||SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 3, 2) = 'SSS' THEN
      V_MERCESTENT     := V_VRESTADOENT;
      V_MERCFORAESTENT := V_FORA_ESTADOENT;
      V_MERCEXTENT     := V_EXTERIORENT;
      V_MERCTOTENT     := V_TOTENT;
      V_MERCESTSAI     := V_VRESTADOSAI;
      V_MERCFORAESTSAI := V_FORA_ESTADOSAI;
      V_MERCEXTSAI     := V_EXTERIORSAI;
      V_MERCTOTSAI     := V_TOTSAI;
   END IF;

   V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
   V_DADOS_0200 := '0200'                                                                        ||
                   '000000000000001'                                                             ||
                   'N'                                                                           ||
                   SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 1, 7)                              ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_VRESTADOENT,'0'), '0000000000000.00'),'.',''))    ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_FORA_ESTADOENT,'0'), '0000000000000.00'),'.','')) ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_EXTERIORENT,'0'), '0000000000000.00'),'.',''))    ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_TOTENT,'0'), '0000000000000.00'),'.',''))         ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_VRESTADOSAI,'0'), '0000000000000.00'),'.',''))    ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_FORA_ESTADOSAI,'0'), '0000000000000.00'),'.','')) ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_EXTERIORSAI,'0'), '0000000000000.00'),'.',''))    ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_TOTSAI,'0'), '0000000000000.00'),'.',''))         ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCESTENT,'0'), '0000000000000.00'),'.',''))     ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCFORAESTENT,'0'), '0000000000000.00'),'.','')) ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCEXTENT,'0'), '0000000000000.00'),'.',''))     ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCTOTENT,'0'), '0000000000000.00'),'.',''))     ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCESTSAI,'0'), '0000000000000.00'),'.',''))     ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCFORAESTSAI,'0'), '0000000000000.00'),'.','')) ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCEXTSAI,'0'), '0000000000000.00'),'.',''))     ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_MERCTOTSAI,'0'), '0000000000000.00'),'.',''))     ||
                   RPAD(' ', 88, ' ')                                                            ||
                   LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

   INSERT INTO ARQMAGNETICO
      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
      (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0200, P_NRSEQARQMAG);

   --Registro "0300"

   /*A ficha de ajustes so e preenchida quando houver incidencia de ICMS e, as atividades exercidas pela empresa sao
     Industria, Comercio, Producao Agropecuaria, Extracao Vegetal ou Atividade Pesqueira.*/
   IF SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 1, 1)||SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 3, 1) = 'SS' THEN

      /*Imposto Retido por ST - 005 e 011*/
      BEGIN
         SELECT SUM(DECODE(A.IDENTRSAIDOP, 'S', ROUND(IP.VRIMPOSTONF,2), 0)) AS VRSTSAIDA,
                SUM(DECODE(A.IDENTRSAIDOP, 'E', ROUND(IP.VRCONTABILNF,2), 0)) AS VRSTENTRADA
           INTO V_VRSTSAIDA, V_VRSTENTRADA
           FROM IMPOSTONF IP,
                (SELECT DISTINCT N.IDENTRSAIDOP, N.NRLANCTONF, N.CDFILIAL
                   FROM MAPAAPURAC M, NOTAFISCAL N, IMPOSTONF I
                  WHERE M.CDEMPRESA    =  P_CDEMPRESA
                    AND M.CDINSCESTA   =  P_CDINSCESTA
                    AND M.CDIMPOSTO    =  P_CDIMPOSTO
                    AND M.DTINIPERIODO >= V_DTINICIAL
                    AND M.DTFIMPERIODO <= V_DTFINAL
                    AND M.NRSEQUMAPAPU =  I.NRSEQUMAPAPU
                    AND I.NRLANCTONF   =  N.NRLANCTONF
                    AND I.CDFILIAL     =  N.CDFILIAL) A,
                (SELECT CDIMPOSTRIB
                   FROM IMPOSTO
                  WHERE CDIMPOSTONFE = P_CDIMPOSTO) B
          WHERE A.NRLANCTONF = IP.NRLANCTONF
            AND A.CDFILIAL   = IP.CDFILIAL
            AND IP.CDIMPOSTO = B.CDIMPOSTRIB;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRSTSAIDA   := NULL;
            V_VRSTENTRADA := NULL;
      END;

      /*001 - Operacoes relativas ao ativo imobilizado*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00007';

      BEGIN
         SELECT SUM(ROUND(IP.VRCONTABILNF,2)) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG   = '001';
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*002 - Operacoes relativas ao uso ou consumo*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00008';

      BEGIN
         SELECT SUM(ROUND(IP.VRCONTABILNF,2)) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG   = '002';
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*003 - IPI nas entradas de materia prima*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00010';

      BEGIN
         SELECT SUM(ROUND(DECODE(A.IDENTRSAIDOP,'E',IP.VRBASECALCNF,0),2)) AS VRBCIPIE,
                SUM(ROUND(DECODE(A.IDENTRSAIDOP,'S',IP.VRBASECALCNF,0),2)) AS VRBCIPIS,
                SUM(ROUND(DECODE(A.IDENTRSAIDOP,'S',IP.VRIMPOSTONF,0),2)) AS VRIMPOSIPIS
           INTO V_VRBCIPIE, V_VRBCIPIS, V_VRIMPIPIS
           FROM IMPOSTONF IP, CFOPLIVROMAG C,
                (SELECT N.IDENTRSAIDOP, N.NRLANCTONF, N.CDFILIAL
                   FROM MAPAAPURAC M, NOTAFISCAL N, IMPOSTONF I
                  WHERE M.CDEMPRESA    =  P_CDEMPRESA
                    AND M.CDINSCESTA   =  P_CDINSCESTA
                    AND M.CDIMPOSTO    =  P_CDIMPOSTO
                    AND M.DTINIPERIODO >= V_DTINICIAL
                    AND M.DTFIMPERIODO <= V_DTFINAL
                    AND M.NRSEQUMAPAPU =  I.NRSEQUMAPAPU
                    AND I.NRLANCTONF   =  N.NRLANCTONF
                    AND I.CDFILIAL     =  N.CDFILIAL) A
           WHERE A.NRLANCTONF    = IP.NRLANCTONF
             AND A.CDFILIAL      = IP.CDFILIAL
             AND IP.CDIMPOSTO    = '10'
             AND IP.IDIMPOSTONF IN ('1','2')
             AND IP.CDFISCOPERNF = C.CDCFOPLMAG
             AND C.CDLIVROMAG    = P_CDLIVROMAG
             AND C.CDLAYOUTLMAG IN ('003','008');
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRBCIPIE  := NULL;
            V_VRBCIPIS  := NULL;
            V_VRIMPIPIS := NULL;
      END;

      /*O valor e obtido aplicando-se ao total do IPI das entradas de materia prima o mesmo percentual
        das parcelas do IPI das saidas ajustadas no item 08*/
      IF  V_VRBCIPIS <> 0 THEN
         V_VRAJUSTE := ((V_VRBCIPIE*V_VRIMPIPIS)/V_VRBCIPIS);
      ELSE
         V_VRAJUSTE := 0;
      END IF;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*004 - Operacoes/prestacoes que nao sao FG do ICMS ou nao utilizadas no VA de mercadorias (especificadas)*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00036';

      BEGIN
         SELECT SUM(DECODE(CDLAYOUTLMAG, '004', ROUND(IP.VRCONTABILNF,2), ABS(ROUND(IP.VRCONTABILNF,2)-ROUND(IP.VRBASECALCNF,2)))) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG  IN ('004','104');
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*005-ICMS retido por substituicao tributaria*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00025';

      BEGIN
         SELECT SUM(ROUND(IP.VRCONTABILNF,2)) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG   = '005';
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_VRAJUSTE := NVL(V_VRAJUSTE,0)+ NVL(V_VRSTENTRADA,0);

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*006 - Operacoes relativas ao ativo imobilizado*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00002';

      BEGIN
         SELECT SUM(ROUND(IP.VRCONTABILNF,2)) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG   = '006';
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*007 - Operacoes relativas ao uso ou consumo*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00003';

      BEGIN
         SELECT SUM(ROUND(IP.VRCONTABILNF,2)) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG   = '007';
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*008 - IPI que nao integra a base de calculo de ICMS*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00005';

      V_VRAJUSTE := V_VRIMPIPIS; /*Valor do imposto de saida que nao integra a BC do ICMS*/

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*009 - IPI que integra a base de calculo de ICMS*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00029';

      BEGIN
         SELECT SUM(ROUND(IP.VRIMPOSTONF,2)) AS VRIPIS
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, CFOPLIVROMAG C,
                (SELECT N.IDENTRSAIDOP, N.NRLANCTONF, N.CDFILIAL
                   FROM MAPAAPURAC M, NOTAFISCAL N, IMPOSTONF I
                  WHERE M.CDEMPRESA    =  P_CDEMPRESA
                    AND M.CDINSCESTA   =  P_CDINSCESTA
                    AND M.CDIMPOSTO    =  P_CDIMPOSTO
                    AND M.DTINIPERIODO >= V_DTINICIAL
                    AND M.DTFIMPERIODO <= V_DTFINAL
                    AND M.NRSEQUMAPAPU =  I.NRSEQUMAPAPU
                    AND I.NRLANCTONF   =  N.NRLANCTONF
                    AND I.CDFILIAL     =  N.CDFILIAL
                    AND N.IDENTRSAIDOP = 'S') A
           WHERE A.NRLANCTONF    = IP.NRLANCTONF
             AND A.CDFILIAL      = IP.CDFILIAL
             AND IP.CDIMPOSTO    = '10'
             AND IP.IDIMPOSTONF  = '4'
             AND IP.CDFISCOPERNF = C.CDCFOPLMAG
             AND C.CDLIVROMAG    = P_CDLIVROMAG
             AND C.CDLAYOUTLMAG  = '009';
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*010 - Operacoes/prestacoes que nao sao FG do ICMS ou nao utilizadas no VA de mercadorias (especificadas)*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00037';

      BEGIN
         SELECT SUM(DECODE(CDLAYOUTLMAG, '010', ROUND(IP.VRCONTABILNF,2), ABS(ROUND(IP.VRCONTABILNF,2)-ROUND(IP.VRBASECALCNF,2)))) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG  IN ('010','110');
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*011 - ICMS retido por substituicao tributaria*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00024';

      BEGIN
         SELECT SUM(ROUND(IP.VRCONTABILNF,2)) AS VRAJUSTE
           INTO V_VRAJUSTE
           FROM IMPOSTONF IP, NOTAFISCAL NF, CFOPLIVROMAG C, MAPAAPURAC MP
          WHERE MP.CDIMPOSTO     = P_CDIMPOSTO
            AND MP.CDEMPRESA     = P_CDEMPRESA
            AND MP.CDINSCESTA    = P_CDINSCESTA
            AND MP.DTINIPERIODO >= V_DTINICIAL
            AND MP.DTFIMPERIODO <= V_DTFINAL
            AND IP.NRSEQUMAPAPU  = MP.NRSEQUMAPAPU
            AND IP.NRLANCTONF    = NF.NRLANCTONF
            AND IP.CDFILIAL      = NF.CDFILIAL
            AND IP.CDFISCOPERNF  = C.CDCFOPLMAG
            AND C.CDLIVROMAG     = P_CDLIVROMAG
            AND C.CDLAYOUTLMAG   = '011';
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE:= NULL;
      END;

      V_VRAJUSTE := NVL(V_VRAJUSTE,0)+ NVL(V_VRSTSAIDA,0);

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*012 - Estoque inicial*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00013';

      IF (P_DTINICIO IS NOT NULL) AND (TO_CHAR(P_DTINICIO,'YYYY') = P_DTANO) THEN
         V_DTESTOQUE := P_DTINICIO;
      ELSE
         V_DTESTOQUE := TO_DATE('01/01/'||(P_DTANO-1));
      END IF;

      BEGIN
         SELECT SUM(ROUND(I.VRTOTINVFISC,2))
           INTO V_VRAJUSTE
           FROM INVENTFISC I, PRODUTO P
             WHERE I.CDEMPRESA    = P_CDEMPRESA
              AND I.CDINSCESTA   = P_CDINSCESTA
              AND I.CDPRODUTO    = P.CDPRODUTO
              AND I.QTESTINVFISC <> 0
              AND I.DTINVEFISCAL = (SELECT MAX(DTINVEFISCAL)
                                             FROM INVENTFISC V  , PRODUTO PR
                                            WHERE V.DTINVEFISCAL <= V_DTESTOQUE
                                             AND V.CDEMPRESA = P_CDEMPRESA
                                             AND V.CDINSCESTA   = P_CDINSCESTA
                                             AND V.CDPRODUTO    = PR.CDPRODUTO
                                             AND V.QTESTINVFISC <> 0);

      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE := NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*013 - Estoque final*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00014';

      IF P_CONTRIBU = 'S' THEN
         V_DTESTOQUE := P_DTENCER;
      ELSE
         V_DTESTOQUE := TO_DATE('01/01/'||P_DTANO);
      END IF;

      BEGIN
         SELECT SUM(ROUND(I.VRTOTINVFISC,2))
           INTO V_VRAJUSTE
           FROM INVENTFISC I, PRODUTO P
             WHERE I.CDEMPRESA   = P_CDEMPRESA
              AND I.CDINSCESTA   = P_CDINSCESTA
              AND I.CDPRODUTO    = P.CDPRODUTO
              AND I.QTESTINVFISC <> 0
              AND I.DTINVEFISCAL = (SELECT MAX(DTINVEFISCAL)
                                             FROM INVENTFISC V  , PRODUTO PR
                                            WHERE V.DTINVEFISCAL <= V_DTESTOQUE
                                             AND V.CDEMPRESA    = P_CDEMPRESA
                                             AND V.CDINSCESTA   = P_CDINSCESTA
                                             AND V.CDPRODUTO    = PR.CDPRODUTO
                                             AND V.QTESTINVFISC <> 0);
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRAJUSTE := NULL;
      END;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

      /*014 - Importacoes destinadas a industrializacao ou comercializacao*/
      V_VRAJUSTE := 0;
      V_CODAJUSTE := '00031';

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0300 := '0300'                           ||
                      '000000000000001'                ||
                      'N'                              ||
                      LPAD(NVL(V_CODAJUSTE,'0'),5,'0') ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRAJUSTE,'0'),'0000000000000.00'),'.','')) ||
                      RPAD(' ', 315, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0300, P_NRSEQARQMAG);

      V_VRTOTAJUSTE := V_VRTOTAJUSTE + NVL(V_VRAJUSTE,0);

   END IF;

   --Registro "0400"

   /*Aquisicoes de produtos agropecuarios/pesqueiros sem nota fiscal de produtor*/
   FOR C_REG0400 IN (SELECT '0400'                                                                ||
                            '000000000000001'                                                     ||
                            'N'                                                                   ||
                            '00021'                                                               ||
                            LPAD(NVL(CDMUNIEXPO,'0'),8,'0')                                       ||
                            LTRIM(REPLACE(TO_CHAR(NVL(VRDISTRIB,'0'),'0000000000000.00'),'.','')) ||
                            RPAD(' ', 291, ' ')   AS DADOS_0400, VRDISTRIB
                       FROM (SELECT M.CDMUNIEXPO, SUM(ROUND(VRNOTAFISC,2)) AS VRDISTRIB
                               FROM NOTAFISCAL N, FORNECEDOR F, ENDEFORN E, MUNICIPIO M
                              WHERE N.CDTIPOOPER   = '08'
                                AND DTEMISSAO BETWEEN V_DTINICIAL AND V_DTFINAL
                                AND N.CDEMPRESA    = P_CDEMPRESA
                                AND N.CDINSCESTA   = P_CDINSCESTA
                                AND N.CDFORNECED   = F.CDFORNECED
                                AND F.CDFORNECED   = E.CDFORNECED
                                AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                             GROUP BY M.CDMUNIEXPO)) LOOP

      V_VRTOTDISTRIB := V_VRTOTDISTRIB + C_REG0400.VRDISTRIB;
      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), C_REG0400.DADOS_0400||LPAD(TO_CHAR(V_CONT_LINHA), 21, '0'), P_NRSEQARQMAG);
   END LOOP;

   /*Valor Adicionado - Situacao especial de resp. por dispensa de inscricao e/ou registro centralizado*/
   IF SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 6, 1) = 'S' THEN
      FOR C_REG0400 IN (SELECT '0400'                                                                ||
                               '000000000000001'                                                     ||
                               'N'                                                                   ||
                               '00032'                                                               ||
                               LPAD(NVL(CDMUNIEXPO,'0'),8,'0')                                       ||
                               LTRIM(REPLACE(TO_CHAR(NVL((VRSAIDA-VRENTRADA),'0'),'0000000000000.00'),'.','')) ||
                               RPAD(' ', 291, ' ')   AS DADOS_0400, (VRSAIDA-VRENTRADA) AS VRDISTRIB
                         FROM (SELECT SUM(DECODE(IDENTRSAIDOP, 'S', ROUND(I.VRCONTABILNF,2), 0)) AS VRSAIDA,
                                      SUM(DECODE(IDENTRSAIDOP, 'E', ROUND(I.VRCONTABILNF,2), 0)) AS VRENTRADA,
                                      CDMUNIEXPO
                                 FROM MAPAAPURAC M, NOTAFISCAL N, IMPOSTONF I,
                                      FILIAL F, ENDEFILI EF, MUNICIPIO MU
                                WHERE M.CDEMPRESA    =  P_CDEMPRESA
                                  AND M.CDINSCESTA   =  P_CDINSCESTA
                                  AND M.CDIMPOSTO    =  P_CDIMPOSTO
                                  AND M.DTINIPERIODO >= V_DTINICIAL
                                  AND M.DTFIMPERIODO <= V_DTFINAL
                                  AND M.NRSEQUMAPAPU =  I.NRSEQUMAPAPU
                                  AND I.NRLANCTONF   =  N.NRLANCTONF
                                  AND I.CDFILIAL     =  N.CDFILIAL
                                  AND ((IDIMPOSTONF <> '3') OR (IDIMPOSTONF IS NULL))
                                  AND DECODE(IDENTRSAIDOP, 'E', CDFILIRECE, CDFILIEMIT) = F.CDFILIAL
                                  AND NVL(IDTPENDEFILI,'P') = 'P'
                                  AND EF.CDFILIAL    =  F.CDFILIAL
                                  AND EF.CDPAIS      =  MU.CDPAIS
                                  AND EF.SGESTADO    =  MU.SGESTADO
                                  AND EF.CDMUNICIPIO =  MU.CDMUNICIPIO
                                GROUP BY CDMUNIEXPO)
                        WHERE VRSAIDA > VRENTRADA
                        ORDER BY CDMUNIEXPO) LOOP

         V_VRTOTDISTRIB := V_VRTOTDISTRIB + C_REG0400.VRDISTRIB;
         V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;

         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            (LPAD(V_CONT_LINHA, 10, '0'), C_REG0400.DADOS_0400||LPAD(TO_CHAR(V_CONT_LINHA), 21, '0'), P_NRSEQARQMAG);
      END LOOP;
   END IF;

   --Registro "0500"

   WHILE (V_CONT_MES < 12) LOOP
      V_CONT_MES := V_CONT_MES + 1;

      BEGIN
         --Receita bruta do estabelecimento
         SELECT SUM(ROUND(VRNOTAFISC,2)) AS VRRECBRUTA
           INTO V_VRRECBRESTA
           FROM NOTAFISCAL N, TIPOOPERAC T
          WHERE N.DTEMISSAO    BETWEEN V_DTINICIAL AND V_DTFINAL
            AND LPAD(TO_CHAR(N.DTEMISSAO, 'MM'), 2, '0') = LPAD(TO_CHAR(V_CONT_MES), 2, '0')
            AND N.IDSTATUS     IN ('A','E')    --Retirar descontos
            AND N.CDEMPRESA    = P_CDEMPRESA
            AND N.CDINSCESTA   = P_CDINSCESTA
            AND N.IDENTRSAIDOP = 'S'
            AND N.IDENTRSAIDOP = T.IDENTRSAIDOP
            AND N.CDTIPOOPER   = T.CDTIPOOPER
            AND T.IDTPFATAPURA IS NOT NULL
            AND N.IDSISTEMA    NOT IN ('TMP','PAG','REC');
      EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_VRRECBRESTA := NULL;
      END;

      IF SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 8, 1) = 'S' THEN
         BEGIN
            --Receita bruta da empresa
           SELECT SUM(ROUND(VRNOTAFISC,2)) AS VRRECBRUTA
           INTO V_VRRECBREMPR
           FROM NOTAFISCAL N, TIPOOPERAC T
          WHERE N.DTEMISSAO    BETWEEN V_DTINICIAL AND V_DTFINAL
            AND LPAD(TO_CHAR(N.DTEMISSAO, 'MM'), 2, '0') = LPAD(TO_CHAR(V_CONT_MES), 2, '0')
            AND N.IDSTATUS     IN ('A','E')    --Retirar descontos
            AND N.CDEMPRESA    = P_CDEMPRESA
            AND N.IDENTRSAIDOP = 'S'
            AND N.IDENTRSAIDOP = T.IDENTRSAIDOP
            AND N.CDTIPOOPER   = T.CDTIPOOPER
            AND T.IDTPFATAPURA IS NOT NULL
            AND N.IDSISTEMA    NOT IN ('TMP','PAG','REC');
         EXCEPTION
              WHEN NO_DATA_FOUND THEN
                 V_VRRECBREMPR := NULL;
         END;
      END IF;

      IF SUBSTR(NVL(P_STIDREGISTRO, 'NNNNNNNNNNN'), 9, 1) = 'S' THEN
         V_VRRECBREMPR := V_VRRECBRESTA;
      END IF;

      V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
      V_DADOS_0500 := '0500'                           ||
                      '000000000000001'                ||
                      LPAD(TO_CHAR(V_CONT_MES),2,'0')  ||
                      'N'                              ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRRECBRESTA,'0'),'0000000000000.00'),'.','')) ||
                      LTRIM(REPLACE(TO_CHAR(NVL(V_VRRECBREMPR,'0'),'0000000000000.00'),'.','')) ||
                      '000000000000000'                ||
                      '000000000000000'                ||
                      RPAD(' ', 273, ' ')              ||
                      LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_0500, P_NRSEQARQMAG);

      V_TOTAL := NVL(V_TOTAL,0) + NVL(V_VRRECBRESTA,0) + NVL(V_VRRECBREMPR,0);

   END LOOP;

   -- Registro "9999".
   V_TOTAL := NVL(V_TOTAL,0)      + NVL(V_VRESTADOENT,0) + NVL(V_FORA_ESTADOENT,0) + NVL(V_EXTERIORENT,0) +
              NVL(V_TOTENT,0)     + NVL(V_VRESTADOSAI,0) + NVL(V_FORA_ESTADOSAI,0) + NVL(V_EXTERIORSAI,0) +
              NVL(V_TOTSAI,0)     + NVL(V_MERCESTENT,0)  + NVL(V_MERCFORAESTENT,0) + NVL(V_MERCEXTENT,0)  +
              NVL(V_MERCTOTENT,0) + NVL(V_MERCESTSAI,0)  + NVL(V_MERCFORAESTSAI,0) + NVL(V_MERCEXTSAI,0)  +
              NVL(V_MERCTOTSAI,0) + NVL(V_VRTOTAJUSTE,0) + NVL(V_VRTOTDISTRIB,0);

   V_CONT_LINHA := NVL(V_CONT_LINHA,0) + 1;
   V_DADOS_9999 := '9999'  ||
                   LTRIM(REPLACE(TO_CHAR(NVL(V_TOTAL,'0'), '00000000000000000000000.00'),'.','')) ||
                   '00001' ||
                   LPAD(TO_CHAR(V_CONT_LINHA), 5, '0') ||
                   RPAD(' ', 316, ' ') ||
                   LPAD(TO_CHAR(V_CONT_LINHA), 5, '0');

   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     (LPAD(V_CONT_LINHA, 10, '0'), V_DADOS_9999, P_NRSEQARQMAG);
END;
/