CREATE OR REPLACE FUNCTION SPED_BLOCO1(
   P_CDIMPOSTO       IN IMPOSTO.CDIMPOSTO%TYPE,
   P_CDEMPRESA       IN EMPRESA.CDEMPRESA%TYPE,
   P_CDINSCESTA      IN EMPRESA.CDINSCESTA%TYPE,
   P_DTINICIAL       IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL         IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_VERSAO          IN VARCHAR2,
   P_NRSEQARQMAG     IN ARQMAGNETICO.NRSEQARQMAG%TYPE,
   P_OBRIGREGBL1     IN VARCHAR2,
   P_TOTALIZA        IN NUMBER,
   P_CDLIVROMAG      IN LIVROMAGNETICO.CDLIVROMAG%TYPE,
   P_CDLIVROMAGADIC  IN LIVROMAGADIC.CDLIVROMAGADIC%TYPE,
   P_IDORIGLIVROADIC IN NOTAFISCAL.IDSTATUS%TYPE,
   P_DTINIVAF        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINVAF        IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_AGRUPPROD       IN GRUPPROD.CDGRUPPROD%TYPE,
   P_CDINSCENTR      IN VARCHAR2) RETURN NUMBER
AS
   V_CONTREG1         NUMBER;
   V_NRSEQUMAPAPU     VARCHAR2(10);
   V_OBRIGREGBL1      VARCHAR2(50);
   V_SEQUPROD         NUMBER;
   V_COD_PAR          VARCHAR2(100);
   V_PRODUTO          VARCHAR2(100);
   V_NOTA_ANT         VARCHAR2(20);
   V_CDSITUCRT        VARCHAR2(01);
   V_CDPAIS           VARCHAR2(04);
   V_SGESTADO         VARCHAR2(02);
   V_CDMUNIEXPO       VARCHAR2(10);
   V_UNID             VARCHAR2(10);
   V_SAIDASDIPAM      NUMBER;
   V_ENTRADASDIPAM    NUMBER;
   V_VRADICIONADO     NUMBER;
   V_TPAPURACAO       VARCHAR2(01);
   V_CD1921ENTR       VARCHAR2(10);
   V_CD1921SAID       VARCHAR2(10);
   V_CD1921COMPL      VARCHAR2(10);
   V_CD1921REST       VARCHAR2(10);
   V_CDE220COMPL      VARCHAR2(10);
   V_CDE220REST       VARCHAR2(10);
   V_ALIQINTERNA      NUMBER;
   V_AJUSTEDEB        NUMBER;
   V_RESTITUIR        NUMBER;
   V_AJUSTECRED       NUMBER;
   V_SALDOAPUR        NUMBER;
   V_COMPLEMENTAR     NUMBER;
   V_DSARQ1900        VARCHAR2(1000);
   V_EXISTEE200       VARCHAR2(01);
   V_REG_E220         VARCHAR2(1000);
   V_CONTREGE         NUMBER;
   V_CDFILIAL         VARCHAR2(10);
   V_CDPRODUTO        VARCHAR2(20);
   V_IDGERAJUST       VARCHAR2(01);
   V_IDAPURLUCPRE     VARCHAR2(01);
   V_IDUTSUBAPURCP    VARCHAR2(01);
   V_IDINDICSUBAPURCP VARCHAR2(01);
   V_DSOUTRAAPURCP    VARCHAR2(250);
   V_DEB1900CP        NUMBER;
   V_AJSUBAPUROC      NUMBER;
   V_AJSUBAPURED      NUMBER;
   V_AJSUBAPUROD      NUMBER;
   V_AJSUBAPUREC      NUMBER;
   V_AJSUBAPURDD      NUMBER;
   V_AJSUBAPURDE      NUMBER;
   V_TOTSUBAPUR       NUMBER;
BEGIN
   V_SEQUPROD := NVL(P_TOTALIZA,0);

   /*VERIFICA SE A EMPRESA E DO SIMPLES NACIONAL, '3' NAO E DO SIMPLES, APENAS 1 E 2*/
   SELECT NVL(MAX(CDSITUCRT), '3') CDSITUCRT
     INTO V_CDSITUCRT
     FROM PARAMEMPRESA
    WHERE CDEMPRESA = P_CDEMPRESA;

   IF V_CDSITUCRT IN('2','3') THEN
       BEGIN
          SELECT NRSEQUMAPAPU
            INTO V_NRSEQUMAPAPU
            FROM MAPAAPURAC M
           WHERE M.CDEMPRESA = P_CDEMPRESA
             AND M.CDINSCESTA = P_CDINSCESTA
             AND M.CDIMPOSTO = P_CDIMPOSTO
             AND M.DTINIPERIODO = P_DTINICIAL
             AND M.DTFIMPERIODO = P_DTFINAL;
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             V_NRSEQUMAPAPU := NULL;
       END;
   END IF;

   IF V_CDSITUCRT = '1' THEN
       BEGIN
          SELECT NRSEQUMAPAPU
            INTO V_NRSEQUMAPAPU
            FROM MAPAAPURACSN M
           WHERE M.CDEMPRESA = P_CDEMPRESA
             AND M.DTINIPERIODO = P_DTINICIAL
             AND M.DTFIMPERIODO = P_DTFINAL;
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             V_NRSEQUMAPAPU := NULL;
       END;
   END IF;

   BEGIN
      SELECT I.CDPAIS, I.SGESTADO, NVL(MU.CDMUNICIBGE,MU.CDMUNICIPIO), I.IDUTSUBAPURCP,
             I.IDINDICSUBAPURCP, I.DSOUTRAAPURCP, I.IDAPURLUCPRE
        INTO V_CDPAIS, V_SGESTADO, V_CDMUNIEXPO, V_IDUTSUBAPURCP,
             V_IDINDICSUBAPURCP, V_DSOUTRAAPURCP, V_IDAPURLUCPRE
        FROM INSCRESTAD I, MUNICIPIO MU
       WHERE CDEMPRESA  = P_CDEMPRESA
         AND CDINSCESTA = P_CDINSCESTA
         AND I.CDPAIS      = MU.CDPAIS
         AND I.SGESTADO    = MU.SGESTADO
         AND I.CDMUNICIPIO = MU.CDMUNICIPIO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDPAIS           := NULL;
         V_SGESTADO         := NULL;
         V_CDMUNIEXPO       := NULL;
         V_IDUTSUBAPURCP    := 'N';
         V_IDINDICSUBAPURCP := NULL;
         V_DSOUTRAAPURCP    := NULL;
         V_IDAPURLUCPRE     := 'N';
   END;

   IF P_VERSAO NOT IN ('003','004','005') THEN
      /* ABERTURA DO BLOCO 1 */
      V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
      INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), '|1001'|| '|' ||'0'|| '|', P_NRSEQARQMAG);

      /* REGISTRO 1010 - OBRIGATORIO A PARTIR DA VERSAO 006 */

      V_OBRIGREGBL1 := SUBSTR(P_OBRIGREGBL1,1,1)  || '|' || /*REGISTRO 1100*/
                       SUBSTR(P_OBRIGREGBL1,2,1)  || '|' || /*REGISTRO 1200*/
                       SUBSTR(P_OBRIGREGBL1,4,1)  || '|' || /*REGISTRO 1300*/
                       SUBSTR(P_OBRIGREGBL1,5,1)  || '|' || /*REGISTRO 1390*/
                       SUBSTR(P_OBRIGREGBL1,6,1)  || '|' || /*REGISTRO 1400*/
                       SUBSTR(P_OBRIGREGBL1,7,1)  || '|' || /*REGISTRO 1500*/
                       SUBSTR(P_OBRIGREGBL1,8,1)  || '|' || /*REGISTRO 1600 E 1601 APOS A VERSAO 016*/
                       SUBSTR(P_OBRIGREGBL1,9,1)  || '|' || /*REGISTRO 1700*/
                       SUBSTR(P_OBRIGREGBL1,10,1) || '|' || /*REGISTRO 1800*/
                       CASE WHEN P_VERSAO >= '013' THEN
                          SUBSTR(P_OBRIGREGBL1,11,1) || '|' || /*REGISTRO 1960*/
                          SUBSTR(P_OBRIGREGBL1,12,1) || '|' || /*REGISTRO 1970*/
                          SUBSTR(P_OBRIGREGBL1,13,1) || '|'    /*REGISTRO 1980*/
                       ELSE '' END                   ||
                       CASE WHEN P_VERSAO >= '014' THEN
                          SUBSTR(P_OBRIGREGBL1,3,1)  || '|' /*REGISTRO 1250*/
                       ELSE '' END;

      V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
      INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), '|1010|'||V_OBRIGREGBL1, P_NRSEQARQMAG);

      IF (SUBSTR(P_OBRIGREGBL1,6,1) = 'S') AND (V_CDSITUCRT IN ('2','3')) THEN
         IF V_SGESTADO = 'RS' THEN
            /*Valores do Anexo XVI - Operacoes Intermunicipais da GIA RS*/
            FOR C_REG1400 IN (SELECT '|1400'       || '|' ||
                                     '09'          || '|' ||
                                     T.CDMUNICIBGE || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(NVL(T.VRSERVICO,0)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(NVL(T.VRSERVICO,0)) AS VALOR, T.CDMUNICIBGE AS CDMUNICIBGE
                                FROM (SELECT SUM(ROUND(I.VRCONTABILNF,2)) AS VRSERVICO,
                                             NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE
                                        FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO P, CFOPLIVROMAG L, FILIAL F, ENDEFILI E, MUNICIPIO M
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND I.CDIMPOSTO    = P.CDIMPOSTO
                                         AND P.CDIMPOSTONFE = P_CDIMPOSTO
                                         AND I.NRLANCTONF   = N.NRLANCTONF
                                         AND I.CDFILIAL     =  N.CDFILIAL
                                         AND N.IDENTRSAIDOP = 'S'
                                         AND ((I.IDIMPOSTONF <> '3') OR (I.IDIMPOSTONF IS NULL))
                                         AND L.CDLIVROMAG   = P_CDLIVROMAGADIC
                                         AND L.CDLAYOUTLMAG = '001'
                                         AND I.CDFISCOPERNF = L.CDCFOPLMAG
                                         AND N.CDFILIEMIT   = F.CDFILIAL
                                         AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                         AND E.CDFILIAL     = F.CDFILIAL
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                       GROUP BY NVL(M.CDMUNICIBGE, M.CDMUNICIPIO))T
                               GROUP BY T.CDMUNICIBGE
                               ORDER BY T.CDMUNICIBGE) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
         ELSIF V_SGESTADO = 'MG' THEN
            /*Mercadoria adiquirida de produtor rural sem emissao de NF pelo remetente*/
            FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                     'Produtos_Agropecuarios'                                                  || '|' ||
                                     NF.CDMUNICIBGE                                                            || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(NF.VRCONTABIL,2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(VRCONTABIL,2)) AS VALOR
                                FROM (SELECT NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2)) AS VRCONTABIL
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDEFORN E, MUNICIPIO M,FORNECEDOR F,
                                             (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND ((N.CDMODDOCFISC = '04') OR (NP.CDMODDOCFISC IS NOT NULL) OR (F.IDFORNPRODRURAL = 'S'))
                                         AND N.IDORIGDESTNF = 'F'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND N.CDFORNECED   = F.CDFORNECED
                                         AND N.CDFORNECED   = E.CDFORNECED
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = V_SGESTADO
                                         AND N.IDENTRSAIDOP = 'E'
                                         AND NVL(E.IDTPENDEFORN,'P') = 'P'
                                         AND IDSTATUSNFE    = 'A'
                                         AND ((I.IDIMPOSTONF <> '3') OR (I.IDIMPOSTONF IS NULL))
                                       GROUP BY NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)) NF
                               GROUP BY NF.CDMUNICIBGE) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
            /*Valores passados no VAF/DAMEF*/
            FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                     'Outras_Entradas_a_Detalhar_por_Municipio'                                || '|' ||
                                     NVL(MU.CDMUNICIBGE, MU.CDMUNICIPIO)                                       || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0),2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0),2)) AS VALOR,
                                     NVL(MU.CDMUNICIBGE, MU.CDMUNICIPIO) AS CDMUNICIBGE
                                FROM IMPOSTONF I, NOTAFISCAL N, ENDEFILI L, MAPAAPURAC M, MUNICIPIO MU, CFOPLIVROMAGADIC C
                               WHERE M.CDIMPOSTO       = P_CDIMPOSTO
                                 AND M.CDEMPRESA       = P_CDEMPRESA
                                 AND M.CDINSCESTA      = P_CDINSCESTA
                                 AND M.DTINIPERIODO BETWEEN P_DTINIVAF AND P_DTFINVAF
                                 AND M.DTFIMPERIODO BETWEEN P_DTINIVAF AND P_DTFINVAF
                                 AND M.NRSEQUMAPAPU    = I.NRSEQUMAPAPU
                                 AND I.CDFILIAL        = N.CDFILIAL
                                 AND I.NRLANCTONF      = N.NRLANCTONF
                                 AND DECODE(N.IDENTRSAIDOP,'S',N.CDFILIEMIT,N.CDFILIRECE) = L.CDFILIAL
                                 AND NVL(L.IDTPENDEFILI,'P') = 'P'
                                 AND L.CDPAIS          = V_CDPAIS
                                 AND L.SGESTADO        = V_SGESTADO
                                 AND C.CDLIVROMAG      = P_CDLIVROMAG
                                 AND C.CDLIVROMAGADIC  = P_CDLIVROMAGADIC
                                 AND C.CDCFOPLMAG      = I.CDFISCOPERNF
                                 AND C.CDLAYOUTLMAG    IN ('001','002')
                                 AND (I.IDIMPOSTONF    <> '3' OR I.IDIMPOSTONF IS NULL)
                                 AND MU.CDPAIS         = L.CDPAIS
                                 AND MU.SGESTADO       = L.SGESTADO
                                 AND MU.CDMUNICIPIO    = L.CDMUNICIPIO
                                 AND P_IDORIGLIVROADIC = 'A'
                               GROUP BY NVL(MU.CDMUNICIBGE, MU.CDMUNICIPIO)
                               UNION ALL
                              SELECT '|1400'                                                                   || '|' ||
                                     'Outras_Entradas_a_Detalhar_por_Municipio'                                || '|' ||
                                     NVL(MU.CDMUNICIBGE, MU.CDMUNICIPIO)                                       || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0),2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0),2)) AS VALOR,
                                     NVL(MU.CDMUNICIBGE, MU.CDMUNICIPIO) AS CDMUNICIBGE
                                FROM IMPOSTONF I, NOTAFISCAL N, ENDEFILI L, MAPAAPURAC M, MUNICIPIO MU, CFOPLIVROMAG C
                               WHERE M.CDIMPOSTO       = P_CDIMPOSTO
                                 AND M.CDEMPRESA       = P_CDEMPRESA
                                 AND M.CDINSCESTA      = P_CDINSCESTA
                                 AND M.DTINIPERIODO BETWEEN P_DTINIVAF AND P_DTFINVAF
                                 AND M.DTFIMPERIODO BETWEEN P_DTINIVAF AND P_DTFINVAF
                                 AND M.NRSEQUMAPAPU    = I.NRSEQUMAPAPU
                                 AND I.CDFILIAL        = N.CDFILIAL
                                 AND I.NRLANCTONF      = N.NRLANCTONF
                                 AND DECODE(N.IDENTRSAIDOP,'S',N.CDFILIEMIT,N.CDFILIRECE) = L.CDFILIAL
                                 AND NVL(L.IDTPENDEFILI,'P') = 'P'
                                 AND L.CDPAIS          = V_CDPAIS
                                 AND L.SGESTADO        = V_SGESTADO
                                 AND C.CDLIVROMAG      = P_CDLIVROMAGADIC
                                 AND C.CDCFOPLMAG      = I.CDFISCOPERNF
                                 AND C.CDLAYOUTLMAG    IN ('001','002')
                                 AND (I.IDIMPOSTONF    <> '3' OR I.IDIMPOSTONF IS NULL)
                                 AND MU.CDPAIS         = L.CDPAIS
                                 AND MU.SGESTADO       = L.SGESTADO
                                 AND MU.CDMUNICIPIO    = L.CDMUNICIPIO
                                 AND P_IDORIGLIVROADIC = 'L'
                               GROUP BY NVL(MU.CDMUNICIBGE, MU.CDMUNICIPIO)) LOOP

               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
         ELSIF V_SGESTADO = 'SP' THEN
            /*Notas de Produtor Rural - Em SP agrupa apenas por Municipio, e n?o por Produto como nos demais estados */
            FOR C_REG1400 IN (SELECT '|1400'      || '|' ||
                                     'SPDIPAM11'  || '|' ||
                                     NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(I.VRCONTABILNF,2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(VRCONTABILNF,2)) AS VALOR
                                FROM IMPOSTONF I, NOTAFISCAL N, ENDEFORN E, MUNICIPIO M, FORNECEDOR F,
                                     (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                        FROM NFPRODRURAL
                                       GROUP BY NRLANCTONF, CDFILIAL) NP
                               WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                 AND I.CDFILIAL     = N.CDFILIAL
                                 AND I.NRLANCTONF   = N.NRLANCTONF
                                 AND (I.IDIMPOSTONF <> '3' OR I.IDIMPOSTONF IS NULL)
                                 AND N.CDFORNECED   = E.CDFORNECED
                                 AND E.CDPAIS       = M.CDPAIS
                                 AND E.SGESTADO     = M.SGESTADO
                                 AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                 AND NVL(E.IDTPENDEFORN,'P') = 'P'
                                 AND N.CDFILIAL     = NP.CDFILIAL(+)
                                 AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                 AND N.CDFORNECED   = F.CDFORNECED(+)
                                 AND ((NP.CDMODDOCFISC IS NOT NULL) OR (N.CDMODDOCFISC = '04') OR (F.IDFORNPRODRURAL = 'S'))
                               GROUP BY NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
            /*Valores passados na DIPAM-B*/
             /*Calculo do Valor Adicionado Dipam de acordo com a formula: VRM = (SVM / SVC) x VAG, onde:
                -VRM - valor de rateio por municipio;
                -SVM - valor total das saidas por municipio;
                -SVC - valos das saidas geral;
                -VAG - diferenca entre Saidas - Entradas.
              Para todos os valores devem ser considerados apenas os CFOP's presentes no livro.*/

            V_SAIDASDIPAM   := 0;
            V_ENTRADASDIPAM := 0;
            V_VRADICIONADO  := 0;

            BEGIN
               SELECT VRSAIDA, VRENTRADA, (VRSAIDA-VRENTRADA) AS VRADICIONADO
                 INTO V_SAIDASDIPAM, V_ENTRADASDIPAM, V_VRADICIONADO
                 FROM (SELECT SUM(DECODE(IDENTRSAIDOP, 'S', ROUND(DECODE(NVL(F.IDFORNPRODRURAL,'N'),'N',I.VRCONTABILNF,0),2),0)) AS VRSAIDA,
                              SUM(DECODE(IDENTRSAIDOP, 'E', ROUND(DECODE(NVL(F.IDFORNPRODRURAL,'N'),'N',I.VRCONTABILNF,0),2),0)) AS VRENTRADA
                         FROM NOTAFISCAL N, IMPOSTONF I, CFOPLIVROMAG L, FORNECEDOR F
                        WHERE I.NRSEQUMAPAPU  = V_NRSEQUMAPAPU
                          AND I.NRLANCTONF    = N.NRLANCTONF
                          AND I.CDFILIAL      = N.CDFILIAL
                          AND N.CDFORNECED    = F.CDFORNECED(+)
                          AND N.CDMODDOCFISC  <> '04'
                          AND ((I.IDIMPOSTONF <> '3') OR (I.IDIMPOSTONF IS NULL))
                          AND L.CDLAYOUTLMAG  = '002'
                          AND I.CDFISCOPERNF  = L.CDCFOPLMAG
                          AND L.CDLIVROMAG    = P_CDLIVROMAGADIC)
                WHERE VRSAIDA > VRENTRADA;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_SAIDASDIPAM   := 0;
                  V_ENTRADASDIPAM := 0;
                  V_VRADICIONADO  := 0;
            END;

            IF V_VRADICIONADO > 0 THEN
               FOR C_REG1400 IN (SELECT '|1400'       || '|' ||
                                        'SPDIPAM22'   || '|' ||
                                        NVL(CDMUNICIBGE,CDMUNICIPIO) || '|' ||
                                        REPLACE(LTRIM(TO_CHAR(((VRSAIDA/V_SAIDASDIPAM)*V_VRADICIONADO), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                        ((VRSAIDA/V_SAIDASDIPAM)*V_VRADICIONADO) AS VALOR
                                   FROM (SELECT SUM(ROUND(DECODE(NVL(F.IDFORNPRODRURAL,'N'),'N',I.VRCONTABILNF,0),2)) AS VRSAIDA,
                                                M.CDMUNICIBGE, M.CDMUNICIPIO
                                           FROM IMPOSTONF I, NOTAFISCAL N, CFOPLIVROMAG L,
                                                ENDEFILI E, MUNICIPIO M, FORNECEDOR F
                                          WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                            AND I.NRLANCTONF   = N.NRLANCTONF
                                            AND I.CDFILIAL     = N.CDFILIAL
                                            AND N.IDENTRSAIDOP = 'S'
                                            AND N.CDFORNECED   = F.CDFORNECED(+)
                                            AND N.CDMODDOCFISC <> '04'
                                            AND (I.IDIMPOSTONF <> '3' OR I.IDIMPOSTONF IS NULL)
                                            AND L.CDLAYOUTLMAG = '002'
                                            AND I.CDFISCOPERNF = L.CDCFOPLMAG
                                            AND L.CDLIVROMAG   = P_CDLIVROMAGADIC
                                            AND N.CDFILIEMIT   = E.CDFILIAL
                                            AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                            AND E.CDPAIS       = M.CDPAIS
                                            AND E.SGESTADO     = M.SGESTADO
                                            AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                          GROUP BY M.CDMUNICIBGE, M.CDMUNICIPIO)
                                  WHERE VRSAIDA > 0) LOOP
                  IF C_REG1400.VALOR > 0 THEN
                     /* REGISTRO 1400 */
                     V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                     INSERT INTO ARQMAGNETICO
                       (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                     VALUES
                       ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
                  END IF;
               END LOOP;
            END IF;
         ELSIF V_SGESTADO = 'ES' THEN  /*GERA AS INFORMACOES DO 1400 PARA O ESTADO DO ES (DOT/ES)*/
            FOR C_REG1400 IN (SELECT '|1400'                                                                || '|' ||
                                     'ESIPM11'                                                              || '|' ||
                                     DECODE(CFOP,'5',NVL(CDMUNICIBGE,CDMUNICIPIO), V_CDMUNIEXPO)            || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(VRCONTABILNF), '999999999990.00')), '.', ',')|| '|' AS ARQ_1400,
                                     SUM(VRCONTABILNF) AS VALOR
                                FROM (SELECT SUBSTR(IP.CDFISCOPERNF,1,1) AS CFOP,
                                             NVL(SUM(ROUND(IP.VRCONTABILNF,2)),0) AS VRCONTABILNF,
                                             NVL(NVL(EF.CDMUNICIPIO,EC.CDMUNICIPIO),EL.CDMUNICIPIO) AS MUNICIPIO,
                                             NVL(NVL(EF.SGESTADO,EC.SGESTADO),EL.SGESTADO) AS SGESTADO,
                                             NVL(NVL(EF.CDPAIS,EC.CDPAIS),EL.CDPAIS) AS CDPAIS
                                        FROM MAPAAPURAC MP, IMPOSTONF IP, NOTAFISCAL NF, IMPOSTO IM, ENDEFORN EF, ENDECLIE EC, ENDEFILI EL, CFOPLIVROMAGADIC CF
                                       WHERE MP.CDEMPRESA       = P_CDEMPRESA
                                         AND MP.CDIMPOSTO       = P_CDIMPOSTO
                                         AND MP.CDINSCESTA      = P_CDINSCESTA
                                         AND MP.DTINIPERIODO   >= P_DTINICIAL
                                         AND MP.DTFIMPERIODO   <= P_DTFINAL
                                         AND IP.NRSEQUMAPAPU    = MP.NRSEQUMAPAPU
                                         AND IP.CDFILIAL        = NF.CDFILIAL
                                         AND IP.NRLANCTONF      = NF.NRLANCTONF
                                         AND NF.IDENTRSAIDOP    = 'S'
                                         AND IP.CDIMPOSTO       = IM.CDIMPOSTO
                                         AND IM.CDIMPOSTONFE    = P_CDIMPOSTO
                                         AND (IP.IDIMPOSTONF <> '3' OR IP.IDIMPOSTONF IS NULL)
                                         AND NF.CDFORNECED      = EF.CDFORNECED(+)
                                         AND NF.CDCLIENTE       = EC.CDCLIENTE(+)
                                         AND NF.CDFILIRECE      = EL.CDFILIAL(+)
                                         AND CF.CDLIVROMAG      = P_CDLIVROMAG
                                         AND CF.CDLIVROMAGADIC  = P_CDLIVROMAGADIC
                                         AND P_IDORIGLIVROADIC  = 'A'
                                         AND CF.CDLAYOUTLMAG    = '002'
                                         AND IP.CDFISCOPERNF    = CF.CDCFOPLMAG
                                         AND EF.IDTPENDEFORN(+) = 'P'
                                         AND EC.IDTPENDECLIE(+) = 'P'
                                         AND EL.IDTPENDEFILI(+) = 'P'
                                       GROUP BY SUBSTR(IP.CDFISCOPERNF,1,1),
                                                NVL(NVL(EF.CDMUNICIPIO,EC.CDMUNICIPIO),EL.CDMUNICIPIO),
                                                NVL(NVL(EF.SGESTADO,EC.SGESTADO),EL.SGESTADO),
                                                NVL(NVL(EF.CDPAIS,EC.CDPAIS),EL.CDPAIS)
                                       UNION ALL
                                      SELECT SUBSTR(IP.CDFISCOPERNF,1,1) AS CFOP,
                                             NVL(SUM(ROUND(IP.VRCONTABILNF,2)),0) AS VRCONTABILNF,
                                             NVL(NVL(EF.CDMUNICIPIO,EC.CDMUNICIPIO),EL.CDMUNICIPIO) AS MUNICIPIO,
                                             NVL(NVL(EF.SGESTADO,EC.SGESTADO),EL.SGESTADO) AS SGESTADO,
                                             NVL(NVL(EF.CDPAIS,EC.CDPAIS),EL.CDPAIS) AS CDPAIS
                                        FROM MAPAAPURAC MP, IMPOSTONF IP, NOTAFISCAL NF, IMPOSTO IM, ENDEFORN EF, ENDECLIE EC, ENDEFILI EL, CFOPLIVROMAG CF
                                       WHERE MP.CDEMPRESA       = P_CDEMPRESA
                                         AND MP.CDIMPOSTO       = P_CDIMPOSTO
                                         AND MP.CDINSCESTA      = P_CDINSCESTA
                                         AND MP.DTINIPERIODO   >= P_DTINICIAL
                                         AND MP.DTFIMPERIODO   <= P_DTFINAL
                                         AND IP.NRSEQUMAPAPU    = MP.NRSEQUMAPAPU
                                         AND IP.CDFILIAL        = NF.CDFILIAL
                                         AND IP.NRLANCTONF      = NF.NRLANCTONF
                                         AND NF.IDENTRSAIDOP    = 'S'
                                         AND IP.CDIMPOSTO       = IM.CDIMPOSTO
                                         AND IM.CDIMPOSTONFE    = P_CDIMPOSTO
                                         AND (IP.IDIMPOSTONF <> '3' OR IP.IDIMPOSTONF IS NULL)
                                         AND NF.CDFORNECED      = EF.CDFORNECED(+)
                                         AND NF.CDCLIENTE       = EC.CDCLIENTE(+)
                                         AND NF.CDFILIRECE      = EL.CDFILIAL(+)
                                         AND CF.CDLIVROMAG      = P_CDLIVROMAGADIC
                                         AND P_IDORIGLIVROADIC  = 'L'
                                         AND CF.CDLAYOUTLMAG    = '002'
                                         AND IP.CDFISCOPERNF    = CF.CDCFOPLMAG
                                         AND EF.IDTPENDEFORN(+) = 'P'
                                         AND EC.IDTPENDECLIE(+) = 'P'
                                         AND EL.IDTPENDEFILI(+) = 'P'
                                       GROUP BY SUBSTR(IP.CDFISCOPERNF,1,1),
                                                NVL(NVL(EF.CDMUNICIPIO,EC.CDMUNICIPIO),EL.CDMUNICIPIO),
                                                NVL(NVL(EF.SGESTADO,EC.SGESTADO),EL.SGESTADO),
                                                NVL(NVL(EF.CDPAIS,EC.CDPAIS),EL.CDPAIS))A, MUNICIPIO MU
                               WHERE MU.CDMUNICIPIO = A.MUNICIPIO
                                 AND MU.SGESTADO    = A.SGESTADO
                                 AND MU.CDPAIS      = A.CDPAIS
                               GROUP BY DECODE(CFOP,'5',NVL(CDMUNICIBGE,CDMUNICIPIO), V_CDMUNIEXPO)) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
            FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                     'ESIPM03'                                                                 || '|' ||
                                     NF.CDMUNICIBGE                                                            || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(IT.VRCONTITIMP,2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(IT.VRCONTITIMP,2)) AS VALOR
                                FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO PR,
                                     (SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDECLIE E, MUNICIPIO M,
                                            (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND NVL(NP.CDMODDOCFISC, N.CDMODDOCFISC) = '04'
                                         AND N.IDORIGDESTNF = 'C'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND N.CDCLIENTE    = E.CDCLIENTE
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = 'ES'
                                         AND NVL(E.IDTPENDECLIE,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)
                                      UNION ALL
                                      SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDEFORN E, MUNICIPIO M,
                                             (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND NVL(NP.CDMODDOCFISC, N.CDMODDOCFISC) = '04'
                                         AND N.IDORIGDESTNF = 'F'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND N.CDFORNECED   = E.CDFORNECED
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = 'ES'
                                         AND NVL(E.IDTPENDEFORN,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)
                                      UNION ALL
                                      SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDEFILI E, MUNICIPIO M,
                                             (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND NVL(NP.CDMODDOCFISC, N.CDMODDOCFISC) = '04'
                                         AND N.IDORIGDESTNF = 'L'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND DECODE(N.IDENTRSAIDOP,'E',N.CDFILIEMIT,N.CDFILIRECE) = E.CDFILIAL
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = 'ES'
                                         AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)) NF
                               WHERE NF.CDFILIAL    = IT.CDFILIAL
                                 AND NF.NRLANCTONF  = IT.NRLANCTONF
                                 AND IT.CDIMPOSTO   = P_CDIMPOSTO
                                 AND (IT.NRITPROIMPOS <> '3' OR IT.NRITPROIMPOS IS NULL)
                                 AND IT.CDFILIAL    = IP.CDFILIAL
                                 AND IT.NRLANCTONF  = IP.NRLANCTONF
                                 AND IT.NRSEQITPROD = IP.NRSEQITPROD
                                 AND IP.CDPRODUTO   = PR.CDPRODUTO
                               GROUP BY NF.CDMUNICIBGE) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
         ELSIF V_SGESTADO = 'BA' THEN  /*GERA AS INFORMACOES DO 1400 PARA O ESTADO DA BA*/
            /*Servicos de Transporte, Servicos de Comunicacao/Telecomunicacao e Distribuicao de Energia Eletrica e Agua*/
            FOR C_REG1400 IN (SELECT '|1400'                      || '|' ||
                                     'BA'||CDLAYOUTLMAG           || '|' ||
                                     NVL(CDMUNICIBGE,CDMUNICIPIO) || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(VRCONTABILNF, '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     VRCONTABILNF AS VALOR
                                FROM (SELECT SUM(ROUND(I.VRCONTABILNF,2)) AS VRCONTABILNF,
                                             M.CDMUNICIBGE, M.CDMUNICIPIO, L.CDLAYOUTLMAG
                                        FROM IMPOSTONF I, NOTAFISCAL N, CFOPLIVROMAG L,
                                             ENDEFILI E, MUNICIPIO M, IMPOSTO IM
                                       WHERE I.NRSEQUMAPAPU  = V_NRSEQUMAPAPU
                                         AND I.NRLANCTONF    = N.NRLANCTONF
                                         AND I.CDFILIAL      = N.CDFILIAL
                                         AND N.IDENTRSAIDOP  = SUBSTR(L.CDLAYOUTLMAG,1,1)
                                         AND (I.IDIMPOSTONF  <> '3' OR I.IDIMPOSTONF IS NULL)
                                         AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                         AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                         AND L.CDLAYOUTLMAG  IN ('E01','E02','E03','S01','S02','S03')
                                         AND I.CDFISCOPERNF  = L.CDCFOPLMAG
                                         AND L.CDLIVROMAG    = P_CDLIVROMAGADIC
                                         AND DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT) = E.CDFILIAL
                                         AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                         AND E.CDPAIS        = M.CDPAIS
                                         AND E.SGESTADO      = M.SGESTADO
                                         AND E.CDMUNICIPIO   = M.CDMUNICIPIO
                                       GROUP BY M.CDMUNICIBGE, M.CDMUNICIPIO, L.CDLAYOUTLMAG)) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
            /*Regimes Especiais*/
            IF P_CDINSCENTR = 'S' THEN
               FOR C_REG1400 IN (SELECT '|1400'                      || '|' ||
                                        'BA'||IDENTRSAIDOP||'04'     || '|' ||
                                        NVL(CDMUNICIBGE,CDMUNICIPIO) || '|' ||
                                        REPLACE(LTRIM(TO_CHAR(VRCONTABILNF, '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                        VRCONTABILNF AS VALOR
                                   FROM (SELECT SUM(ROUND(I.VRCONTABILNF,2)) AS VRCONTABILNF,
                                                M.CDMUNICIBGE, M.CDMUNICIPIO, N.IDENTRSAIDOP
                                           FROM IMPOSTONF I, NOTAFISCAL N,
                                                ENDEFILI E, MUNICIPIO M, IMPOSTO IM
                                          WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                            AND I.NRLANCTONF   = N.NRLANCTONF
                                            AND I.CDFILIAL     = N.CDFILIAL
                                            AND (I.IDIMPOSTONF <> '3' OR I.IDIMPOSTONF IS NULL)
                                            AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                            AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                            AND I.CDFISCOPERNF NOT IN (SELECT L.CDCFOPLMAG
                                                                         FROM CFOPLIVROMAG L
                                                                        WHERE L.CDLAYOUTLMAG IN ('E04','S04')
                                                                          AND L.CDLIVROMAG   = P_CDLIVROMAGADIC)
                                            AND DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT) = E.CDFILIAL
                                            AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                            AND E.CDPAIS       = M.CDPAIS
                                            AND E.SGESTADO     = M.SGESTADO
                                            AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                          GROUP BY M.CDMUNICIBGE, M.CDMUNICIPIO, N.IDENTRSAIDOP)) LOOP
                  IF C_REG1400.VALOR > 0 THEN
                     /* REGISTRO 1400 */
                     V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                     INSERT INTO ARQMAGNETICO
                       (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                     VALUES
                       ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
                  END IF;
               END LOOP;
            END IF;
            /*Exclusoes - IPI e ICMS/ST*/
            /*Operacoes NAO dedutiveis - CFOPs genericos*/
            /*Aquisicao de produto diferido*/
            FOR C_REG1400 IN (SELECT '|1400'                      || '|' ||
                                     'BAE'||CDSUBGRPROD           || '|' ||
                                     NVL(CDMUNICIBGE,CDMUNICIPIO) || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(VRCONTABILNF, '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     VRCONTABILNF AS VALOR
                                FROM (SELECT SUM(ROUND(IT.VRCONTITIMP,2)) AS VRCONTABILNF,
                                             MU.CDMUNICIBGE, MU.CDMUNICIPIO, SUBSTR(PR.CDSUBGRPROD,9,2) AS CDSUBGRPROD
                                        FROM (SELECT DISTINCT I.CDFILIAL, I.NRLANCTONF
                                                FROM IMPOSTONF I
                                               WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU) II,
                                             NOTAFISCAL NF, ITEMPROIMPOS IT, IMPOSTO IM, ITEMPRODUTO IP,
                                             MUNICIPIO MU, FORNECEDOR FO, ENDEFORN EF, PRSUBGRPROD PR
                                       WHERE II.NRLANCTONF   = NF.NRLANCTONF
                                         AND II.CDFILIAL     = NF.CDFILIAL
                                         AND NF.IDENTRSAIDOP = 'E'
                                         AND NVL(IT.NRITPROIMPOS,'1') <> '3'
                                         AND NF.CDFILIAL     = IT.CDFILIAL
                                         AND NF.NRLANCTONF   = IT.NRLANCTONF
                                         AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                                         AND IM.CDIMPOSTONFE = '00'
                                         AND IT.CDFILIAL     = IP.CDFILIAL
                                         AND IT.NRLANCTONF   = IP.NRLANCTONF
                                         AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                         AND IP.CDPRODUTO    = PR.CDPRODUTO
                                         AND PR.CDGRUPPROD   = P_AGRUPPROD
                                         AND NF.CDFORNECED   = FO.CDFORNECED
                                         AND (FO.NRINSESTFORN IS NULL OR FO.IDFORNPRODRURAL = 'S')
                                         AND FO.CDFORNECED   = EF.CDFORNECED
                                         AND NVL(EF.IDTPENDEFORN,'P') = 'P'
                                         AND EF.CDPAIS       = MU.CDPAIS
                                         AND EF.SGESTADO     = MU.SGESTADO
                                         AND EF.CDMUNICIPIO  = MU.CDMUNICIPIO
                                         AND EF.SGESTADO     = 'BA'
                                       GROUP BY MU.CDMUNICIBGE, MU.CDMUNICIPIO, PR.CDSUBGRPROD)) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);
               END IF;
            END LOOP;
         ELSIF V_SGESTADO = 'PR' AND P_CDINSCENTR = 'S' THEN  /*GERA AS INFORMACOES DO 1400 PARA O ESTADO DA PR*/
            FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                     PR.CDARVPROD                                                              || '|' ||
                                     NF.CDMUNICIBGE                                                            || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(IT.VRCONTITIMP,2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(IT.VRCONTITIMP,2)) AS VALOR, PR.CDPRODUTO, PR.SGUNIDADE AS UNID, IP.CDPRODNCMTRANS AS CDCLASFISC
                                FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO PR,
                                     (SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDEFILI E, MUNICIPIO M
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND DECODE(N.IDENTRSAIDOP,'E',N.CDFILIRECE,N.CDFILIEMIT) = E.CDFILIAL
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)) NF
                               WHERE NF.CDFILIAL     = IT.CDFILIAL
                                 AND NF.NRLANCTONF   = IT.NRLANCTONF
                                 AND IT.CDIMPOSTO    = P_CDIMPOSTO
                                 AND IT.CDFISCOPERIT IN (SELECT CDCFOPLMAG
                                                           FROM CFOPLIVROMAG CL
                                                          WHERE CL.CDLIVROMAG = P_CDLIVROMAGADIC)
                                 AND (IT.NRITPROIMPOS <> '3' OR IT.NRITPROIMPOS IS NULL)
                                 AND IT.CDFILIAL     = IP.CDFILIAL
                                 AND IT.NRLANCTONF   = IP.NRLANCTONF
                                 AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                 AND IP.CDPRODUTO    = PR.CDPRODUTO
                               GROUP BY PR.CDPRODUTO, NF.CDMUNICIBGE, PR.CDARVPROD, PR.SGUNIDADE, IP.CDPRODNCMTRANS) LOOP

               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);

                  /*CARREGA UNIDADE DO PRODUTO PARA O REGISTRO 0190*/
                  SELECT MAX(CDCHAVEREG)
                    INTO V_UNID
                    FROM TMP_REGDADOSSPED
                   WHERE CDCHAVEREG = C_REG1400.UNID
                     AND CDREGISTRO = '0190';

                  IF (V_UNID IS NULL) AND (C_REG1400.UNID IS NOT NULL) THEN
                     V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                     INSERT INTO TMP_REGDADOSSPED
                       (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                     VALUES
                       ('0190', V_SEQUPROD, C_REG1400.UNID);
                  END IF;
                  V_UNID := NULL;

                  SELECT MAX(CDCHAVEREG)
                    INTO V_PRODUTO
                    FROM TMP_REGDADOSSPED
                   WHERE CDCHAVEREG = C_REG1400.CDPRODUTO
                     AND CDREGISTRO = '0200';

                  IF (V_PRODUTO IS NULL) AND (C_REG1400.CDPRODUTO IS NOT NULL) THEN
                     V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                     INSERT INTO TMP_REGDADOSSPED
                        (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                     VALUES
                        ('0200', V_SEQUPROD, C_REG1400.CDPRODUTO, C_REG1400.CDCLASFISC);
                  END IF;
               END IF;
            END LOOP;
         ELSE
            FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                     PR.CDARVPROD                                                              || '|' ||
                                     NF.CDMUNICIBGE                                                            || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(ROUND(IT.VRCONTITIMP,2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(ROUND(VRCONTITIMP,2)) AS VALOR, PR.CDPRODUTO, PR.SGUNIDADE AS UNID, IP.CDPRODNCMTRANS AS CDCLASFISC
                                FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO PR,
                                     (SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDECLIE E, MUNICIPIO M,
                                            (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND (N.CDMODDOCFISC = '04' OR NP.CDMODDOCFISC IS NOT NULL)
                                         AND N.IDORIGDESTNF = 'C'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND N.CDCLIENTE    = E.CDCLIENTE
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = V_SGESTADO
                                         AND N.IDENTRSAIDOP = 'E'
                                         AND NVL(E.IDTPENDECLIE,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)
                                      UNION ALL
                                      SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDEFORN E, MUNICIPIO M,FORNECEDOR F,
                                             (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND ((N.CDMODDOCFISC = '04') OR (NP.CDMODDOCFISC IS NOT NULL) OR (F.IDFORNPRODRURAL = 'S'))
                                         AND N.IDORIGDESTNF = 'F'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND N.CDFORNECED   = F.CDFORNECED
                                         AND N.CDFORNECED   = E.CDFORNECED
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = V_SGESTADO
                                         AND N.IDENTRSAIDOP = 'E'
                                         AND NVL(E.IDTPENDEFORN,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)
                                      UNION ALL
                                      SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                        FROM IMPOSTONF I, NOTAFISCAL N, ENDEFILI E, MUNICIPIO M,
                                             (SELECT MAX(CDMODDOCFISC) AS CDMODDOCFISC, NRLANCTONF, CDFILIAL
                                               FROM NFPRODRURAL
                                              GROUP BY NRLANCTONF, CDFILIAL) NP
                                       WHERE I.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                         AND N.CDFILIAL     = I.CDFILIAL
                                         AND N.NRLANCTONF   = I.NRLANCTONF
                                         AND (N.CDMODDOCFISC = '04' OR NP.CDMODDOCFISC IS NOT NULL)
                                         AND N.IDORIGDESTNF = 'L'
                                         AND N.CDFILIAL     = NP.CDFILIAL(+)
                                         AND N.NRLANCTONF   = NP.NRLANCTONF(+)
                                         AND DECODE(N.IDENTRSAIDOP,'E',N.CDFILIEMIT,N.CDFILIRECE) = E.CDFILIAL
                                         AND E.CDPAIS       = M.CDPAIS
                                         AND E.SGESTADO     = M.SGESTADO
                                         AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                         AND M.SGESTADO     = V_SGESTADO
                                         AND N.IDENTRSAIDOP = 'E'
                                         AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                       GROUP BY N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO)) NF
                               WHERE NF.CDFILIAL    = IT.CDFILIAL
                                 AND NF.NRLANCTONF  = IT.NRLANCTONF
                                 AND IT.CDIMPOSTO   = P_CDIMPOSTO
                                 AND (IT.NRITPROIMPOS <> '3' OR IT.NRITPROIMPOS IS NULL)
                                 AND IT.CDFILIAL    = IP.CDFILIAL
                                 AND IT.NRLANCTONF  = IP.NRLANCTONF
                                 AND IT.NRSEQITPROD = IP.NRSEQITPROD
                                 AND IP.CDPRODUTO   = PR.CDPRODUTO
                               GROUP BY PR.CDPRODUTO, NF.CDMUNICIBGE, PR.CDARVPROD, PR.SGUNIDADE, IP.CDPRODNCMTRANS) LOOP
               IF C_REG1400.VALOR > 0 THEN
                  /* REGISTRO 1400 */
                  V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                    (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                    ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);

                  /*CARREGA UNIDADE DO PRODUTO PARA O REGISTRO 0190*/
                  SELECT MAX(CDCHAVEREG)
                    INTO V_UNID
                    FROM TMP_REGDADOSSPED
                   WHERE CDCHAVEREG = C_REG1400.UNID
                     AND CDREGISTRO = '0190';

                  IF (V_UNID IS NULL) AND (C_REG1400.UNID IS NOT NULL) THEN
                     V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                     INSERT INTO TMP_REGDADOSSPED
                       (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                     VALUES
                       ('0190', V_SEQUPROD, C_REG1400.UNID);
                  END IF;
                  V_UNID := NULL;

                  SELECT MAX(CDCHAVEREG)
                    INTO V_PRODUTO
                    FROM TMP_REGDADOSSPED
                   WHERE CDCHAVEREG = C_REG1400.CDPRODUTO
                     AND CDREGISTRO = '0200';

                  IF (V_PRODUTO IS NULL) AND (C_REG1400.CDPRODUTO IS NOT NULL) THEN
                     V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                     INSERT INTO TMP_REGDADOSSPED
                        (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                     VALUES
                        ('0200', V_SEQUPROD, C_REG1400.CDPRODUTO, C_REG1400.CDCLASFISC);
                  END IF;
               END IF;
            END LOOP;
         END IF;
      END IF;

      IF (SUBSTR(P_OBRIGREGBL1,6,1) = 'S') AND (V_CDSITUCRT = '1') THEN  /*SIMPLES NACIONAL*/
         FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                  PR.CDARVPROD                                                              || '|' ||
                                  NF.CDMUNICIBGE                                                            || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(SUM(ROUND(IT.VRCONTITIMP,2)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                  SUM(ROUND(IT.VRCONTITIMP,2)) AS VALOR, PR.CDPRODUTO, PR.SGUNIDADE AS UNID, IP.CDPRODNCMTRANS AS CDCLASFISC
                             FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO PR,
                                  (SELECT N.CDFILIAL, N.NRLANCTONF, M.CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                     FROM IMPOSTONF I, NOTAFISCAL N, ENDECLIE E, MUNICIPIO M
                                    WHERE N.NRSEQUMAPAPUSN = V_NRSEQUMAPAPU
                                      AND N.CDINSCESTA   = P_CDINSCESTA
                                      AND N.CDFILIAL     = I.CDFILIAL
                                      AND N.NRLANCTONF   = I.NRLANCTONF
                                      AND N.CDMODDOCFISC = '04'
                                      AND N.IDORIGDESTNF = 'C'
                                      AND N.CDCLIENTE    = E.CDCLIENTE
                                      AND E.CDPAIS       = M.CDPAIS
                                      AND E.SGESTADO     = M.SGESTADO
                                      AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                      AND NVL(E.IDTPENDECLIE,'P') = 'P'
                                    GROUP BY N.CDFILIAL, N.NRLANCTONF, M.CDMUNICIBGE
                                   UNION ALL
                                   SELECT N.CDFILIAL, N.NRLANCTONF, M.CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                     FROM IMPOSTONF I, NOTAFISCAL N, ENDEFORN E, MUNICIPIO M
                                    WHERE N.NRSEQUMAPAPUSN = V_NRSEQUMAPAPU
                                      AND N.CDINSCESTA   = P_CDINSCESTA
                                      AND N.CDFILIAL     = I.CDFILIAL
                                      AND N.NRLANCTONF   = I.NRLANCTONF
                                      AND N.CDMODDOCFISC = '04'
                                      AND N.IDORIGDESTNF = 'F'
                                      AND N.CDFORNECED   = E.CDFORNECED
                                      AND E.CDPAIS       = M.CDPAIS
                                      AND E.SGESTADO     = M.SGESTADO
                                      AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                      AND NVL(E.IDTPENDEFORN,'P') = 'P'
                                    GROUP BY N.CDFILIAL, N.NRLANCTONF, M.CDMUNICIBGE
                                   UNION ALL
                                   SELECT N.CDFILIAL, N.NRLANCTONF, M.CDMUNICIBGE, SUM(ROUND(I.VRCONTABILNF,2))
                                     FROM IMPOSTONF I, NOTAFISCAL N, ENDEFILI E, MUNICIPIO M
                                    WHERE N.NRSEQUMAPAPUSN = V_NRSEQUMAPAPU
                                      AND N.CDINSCESTA   = P_CDINSCESTA
                                      AND N.CDFILIAL     = I.CDFILIAL
                                      AND N.NRLANCTONF   = I.NRLANCTONF
                                      AND N.CDMODDOCFISC = '04'
                                      AND N.IDORIGDESTNF = 'L'
                                      AND DECODE(N.IDENTRSAIDOP,'E',N.CDFILIEMIT,N.CDFILIRECE) = E.CDFILIAL
                                      AND E.CDPAIS       = M.CDPAIS
                                      AND E.SGESTADO     = M.SGESTADO
                                      AND E.CDMUNICIPIO  = M.CDMUNICIPIO
                                      AND NVL(E.IDTPENDEFILI,'P') = 'P'
                                    GROUP BY N.CDFILIAL, N.NRLANCTONF, M.CDMUNICIBGE) NF
                            WHERE NF.CDFILIAL    = IT.CDFILIAL
                              AND NF.NRLANCTONF  = IT.NRLANCTONF
                              AND IT.CDIMPOSTO   = P_CDIMPOSTO
                              AND (IT.NRITPROIMPOS <> '3' OR IT.NRITPROIMPOS IS NULL)
                              AND IT.CDFILIAL    = IP.CDFILIAL
                              AND IT.NRLANCTONF  = IP.NRLANCTONF
                              AND IT.NRSEQITPROD = IP.NRSEQITPROD
                              AND IP.CDPRODUTO   = PR.CDPRODUTO
                            GROUP BY PR.CDPRODUTO, NF.CDMUNICIBGE, PR.CDARVPROD, PR.SGUNIDADE, IP.CDPRODNCMTRANS) LOOP
            IF C_REG1400.VALOR > 0 THEN
               /* REGISTRO 1400 */
               V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
               INSERT INTO ARQMAGNETICO
                 (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                 ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1400.ARQ_1400, P_NRSEQARQMAG);

               /*CARREGA UNIDADE DE PRODUTO REGISTRO 0190*/
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REG1400.UNID
                  AND CDREGISTRO = '0190';

               IF (V_UNID IS NULL) AND (C_REG1400.UNID IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                  VALUES
                    ('0190', V_SEQUPROD, C_REG1400.UNID);
               END IF;
               V_UNID := NULL;

               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REG1400.CDPRODUTO
                  AND CDREGISTRO = '0200';

               IF (V_PRODUTO IS NULL) AND (C_REG1400.CDPRODUTO IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
                  VALUES
                     ('0200', V_SEQUPROD, C_REG1400.CDPRODUTO, C_REG1400.CDCLASFISC);
               END IF;
            END IF;
         END LOOP;
      END IF;

      IF P_VERSAO >= 016 THEN
         IF SUBSTR(P_OBRIGREGBL1,8,1) = 'S' THEN
            FOR C_REG1601 IN (SELECT '|1601'                                                                                         || '|' ||           -- REG
                                     REPLACE(REPLACE(REPLACE(REPLACE(NVL(CDADMINCART, 'C'||CDCLIENTE), '.'), '-'), '/'), ' ')        || '|' ||           -- COD_PART_IP
                                     ''                                                                                              || '|' ||           -- COD_PART_IT
                                     REPLACE(LTRIM(TO_CHAR(SUM(NVL(VALOR_ICMS,0)), '999999999990.00')), '.', ',')                     || '|' ||           -- TOT_VS
                                     REPLACE(LTRIM(TO_CHAR(SUM(NVL(0,0)), '999999999990.00')), '.', ',')                             || '|' ||           -- TOT_ISS
                                     REPLACE(LTRIM(TO_CHAR(SUM(NVL(VALOR_OUTROS,0)), '999999999990.00')), '.', ',')                     || '|' AS ARQ_1601, -- TOT_OUTROS
                                     NVL(CDADMINCART, 'C'||CDCLIENTE) AS COD_PAR
                                FROM (SELECT SUM(TRUNC((IT.QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))),2) - NVL(IT.VRDESITVEND,0) + NVL(IT.VRACRITVEND,0)) AS VALOR_ICMS, --CAMPO 4
                                             0 AS VALOR_OUTROS,
                                             VD.CDEMPRESA, VD.CDFILIAL, VD.CDCAIXA, 'ICMS' AS TIPO,
                                             VD.CDCLIENTE, TP.CDADMINCART
                                        FROM FILIAL FI,
                                             VENDA VD,
                                             ITEMVENDA IT,
                                             TIPORECE TP,
                                             CAIXAPERS CX,
                                             (SELECT DISTINCT CDFILIAL, CDCAIXA, NRSEQVENDA, DTMOVIMCAIXA, CDTIPORECE
                                                FROM MOVCAIXA) MV,
                                             (SELECT CDFILIAL, CDCAIXA, NRSEQVENDA, NRSEQUITVEND
                                                FROM ITVENDAIMPOS IV, IMPOSTO I
                                               WHERE IV.CDIMPOSTO = I.CDIMPOSTO
                                                 AND I.IDTPIMPOSFIS <> 'F') IP
                                       WHERE VD.CDEMPRESA     = FI.CDEMPRESA
                                         AND VD.CDFILIAL      = FI.CDFILIAL
                                         AND IT.CDFILIAL      = VD.CDFILIAL
                                         AND IT.CDCAIXA       = VD.CDCAIXA
                                         AND IT.NRSEQVENDA    = VD.NRSEQVENDA
                                         AND VD.CDFILIAL      = MV.CDFILIAL
                                         AND VD.CDCAIXA       = MV.CDCAIXA
                                         AND VD.NRSEQVENDA    = MV.NRSEQVENDA
                                         AND IT.CDFILIAL      = IP.CDFILIAL
                                         AND IT.CDCAIXA       = IP.CDCAIXA
                                         AND IT.NRSEQVENDA    = IP.NRSEQVENDA
                                         AND IT.NRSEQUITVEND  = IP.NRSEQUITVEND
                                         AND TP.CDTIPORECE    = MV.CDTIPORECE
                                         AND CX.CDFILIAL      = VD.CDFILIAL
                                         AND CX.CDCAIXAPERS   = VD.CDCAIXA
                                         AND TP.IDTIPORECE IN ('1','2')
                                         AND CX.IDTIPOSISTEMA <> 'SPS'
                                         AND VD.IDSITUVENDA   = 'O'
                                         AND FI.CDEMPRESA     = P_CDEMPRESA
                                         AND FI.CDINSCESTA    = P_CDINSCESTA
                                         AND VD.DTENTRVENDA BETWEEN P_DTINICIAL AND P_DTFINAL
                                       GROUP BY VD.CDEMPRESA, VD.CDFILIAL, VD.CDCAIXA, VD.CDCLIENTE, TP.CDADMINCART
                                       UNION ALL
                                      SELECT 0 AS VALOR_ICMS,
                                             SUM(TRUNC((IT.QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))),2) - NVL(IT.VRDESITVEND,0) + NVL(IT.VRACRITVEND,0)) AS VALOR_OUTROS, --CAMPO 6
                                             VD.CDEMPRESA, VD.CDFILIAL, VD.CDCAIXA, 'OUTROS' AS TIPO,
                                             VD.CDCLIENTE, TP.CDADMINCART
                                        FROM FILIAL FI,
                                             VENDA VD,
                                             ITEMVENDA IT,
                                             TIPORECE TP,
                                             CAIXAPERS CX,
                                             (SELECT DISTINCT CDFILIAL, CDCAIXA, NRSEQVENDA, DTMOVIMCAIXA, CDTIPORECE
                                                FROM MOVCAIXA) MV,
                                             (SELECT CDFILIAL, CDCAIXA, NRSEQVENDA, NRSEQUITVEND
                                                FROM ITVENDAIMPOS IV, IMPOSTO I
                                               WHERE IV.CDIMPOSTO = I.CDIMPOSTO
                                                 AND I.IDTPIMPOSFIS = 'F') IP
                                       WHERE VD.CDEMPRESA     = FI.CDEMPRESA
                                         AND VD.CDFILIAL      = FI.CDFILIAL
                                         AND IT.CDFILIAL      = VD.CDFILIAL
                                         AND IT.CDCAIXA       = VD.CDCAIXA
                                         AND IT.NRSEQVENDA    = VD.NRSEQVENDA
                                         AND VD.CDFILIAL      = MV.CDFILIAL
                                         AND VD.CDCAIXA       = MV.CDCAIXA
                                         AND VD.NRSEQVENDA    = MV.NRSEQVENDA
                                         AND IT.CDFILIAL      = IP.CDFILIAL
                                         AND IT.CDCAIXA       = IP.CDCAIXA
                                         AND IT.NRSEQVENDA    = IP.NRSEQVENDA
                                         AND IT.NRSEQUITVEND  = IP.NRSEQUITVEND
                                         AND TP.CDTIPORECE    = MV.CDTIPORECE
                                         AND CX.CDFILIAL      = VD.CDFILIAL
                                         AND CX.CDCAIXAPERS   = VD.CDCAIXA
                                         AND TP.IDTIPORECE IN ('1','2')
                                         AND CX.IDTIPOSISTEMA <> 'SPS'
                                         AND VD.IDSITUVENDA   = 'O'
                                         AND FI.CDEMPRESA     = P_CDEMPRESA
                                         AND FI.CDINSCESTA    = P_CDINSCESTA
                                         AND VD.DTENTRVENDA BETWEEN P_DTINICIAL AND P_DTFINAL
                                       GROUP BY VD.CDEMPRESA, VD.CDFILIAL, VD.CDCAIXA, VD.CDCLIENTE, TP.CDADMINCART)
                               GROUP BY CDEMPRESA, CDFILIAL, CDCAIXA, CDCLIENTE, CDADMINCART)LOOP
                /* REGISTRO 1601 */
                V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                INSERT INTO ARQMAGNETICO
                        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                VALUES
                        ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1601.ARQ_1601, P_NRSEQARQMAG);

                SELECT MAX(CDCHAVEREG)
                  INTO V_COD_PAR
                  FROM TMP_REGDADOSSPED
                 WHERE CDCHAVEREG = C_REG1601.COD_PAR
                   AND CDREGISTRO = '0150';

                IF (V_COD_PAR IS NULL) AND (C_REG1601.COD_PAR IS NOT NULL) THEN
                   V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                   INSERT INTO TMP_REGDADOSSPED
                        (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                   VALUES
                        ('0150', V_SEQUPROD, C_REG1601.COD_PAR);
                END IF;
             END LOOP;
         END IF;
      ELSE
         IF SUBSTR(P_OBRIGREGBL1,8,1) = 'S' THEN
            /*Rotina alterada para considerar o valor diretamente da movcaixa*/
            FOR C_REG1600 IN (SELECT '|1600'                                                                                                     || '|' ||
                                     REPLACE(REPLACE(REPLACE(REPLACE(NVL(TP.CDADMINCART,'C'||VD.CDCLIENTE),'.'),'-'),'/'),' ')                        || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(TP.IDTIPORECE, '1',VRMOVIVEND, 0)),2),'999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(SUM(DECODE(TP.IDTIPORECE, '2',VRMOVIVEND, 0)),2),'999999999990.00')), '.', ',') || '|' AS ARQ_1600,
                                     NVL(TP.CDADMINCART,'C'||VD.CDCLIENTE) AS COD_PAR
                                FROM MOVCAIXA MV, TIPORECE TP, VENDA VD, CAIXAPERS CX, FILIAL FI
                               WHERE TP.IDTIPORECE IN ('1','2')
                                 AND TP.CDTIPORECE   = MV.CDTIPORECE
                                 AND MV.IDTIPOMOVIVE = 'E'
                                 AND MV.CDFILIAL     = VD.CDFILIAL
                                 AND MV.NRSEQVENDA   = VD.NRSEQVENDA
                                 AND MV.CDCAIXA      = VD.CDCAIXA
                                 AND VD.IDSITUVENDA  = 'O'
                                 AND VD.DTENTRVENDA BETWEEN P_DTINICIAL AND P_DTFINAL
                                 AND CX.CDFILIAL     = VD.CDFILIAL
                                 AND CX.CDCAIXAPERS  = VD.CDCAIXA
                                 AND CX.IDTIPOSISTEMA <> 'SPS'
                                 AND VD.CDEMPRESA    = FI.CDEMPRESA
                                 AND VD.CDFILIAL     = FI.CDFILIAL
                                 AND FI.CDEMPRESA    = P_CDEMPRESA
                                 AND FI.CDINSCESTA   = P_CDINSCESTA
                            GROUP BY NVL(TP.CDADMINCART,'C'||VD.CDCLIENTE))LOOP
               /* REGISTRO 1600 */
               V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1600.ARQ_1600, P_NRSEQARQMAG);

               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_PAR
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REG1600.COD_PAR
                  AND CDREGISTRO = '0150';

               IF (V_COD_PAR IS NULL) AND (C_REG1600.COD_PAR IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                  VALUES
                     ('0150', V_SEQUPROD, C_REG1600.COD_PAR);
               END IF;
            END LOOP;
         END IF;
      END IF;
      /*IF SUBSTR(P_OBRIGREGBL1,9,1) = 'S' THEN
         V_NOTA_ANT := NULL;
         FOR C_REG1700 IN (SELECT '|1700'                                            ||'|'||
                                  DECODE(NF.IDTIPOEMISNFE,'5','01','2','02')         ||'|'||
                                  NF.CDMODDOCFISC                                    ||'|'||
                                  DECODE(NF.IDENTRSAIDOP, 'E', CDSERIEENTR, CDSERIE) ||'|'||
                                  ''                                                 ||'|'||
                                  NF.NRNOTAFISC                                      ||'|'||
                                  NF.NRNOTAFISC                                      ||'|'||
                                  NF.NRPROTOCOLONFE                                  ||'|' AS ARQ_1700,
                                  NF.NRNOTAFISC, NOTA.DTINIPERIODO, NOTA.DTFIMPERIODO
                             FROM NOTAFISCAL NF,
                                  (SELECT DISTINCT IP.CDFILIAL, IP.NRLANCTONF, MP.DTINIPERIODO, MP.DTFIMPERIODO
                                     FROM MAPAAPURAC MP, IMPOSTONF IP, IMPOSTO IM
                                    WHERE MP.NRSEQUMAPAPU = V_NRSEQUMAPAPU
                                      AND MP.NRSEQUMAPAPU = IP.NRSEQUMAPAPU) NOTA
                            WHERE NOTA.CDFILIAL   = NF.CDFILIAL
                              AND NOTA.NRLANCTONF = NF.NRLANCTONF
                              AND NF.IDENTRSAIDOP = 'S'
                              AND NF.IDSTATUS    <> 'C'
                              AND NF.IDTIPOEMISNFE IN ('5','2')
                            ORDER BY LPAD(NF.NRNOTAFISC,12,'0')) LOOP

            IF V_NOTA_ANT IS NOT NULL THEN
               FOR C_REG1710 IN (SELECT '|1710' ||'|'||
                                        NUM_DOC ||'|'||
                                        NUM_DOC ||'|' AS ARQ_1710
                                   FROM
                                      (SELECT NF.NRNOTAFISC AS NUM_DOC
                                         FROM NOTAFISCAL NF
                                        WHERE NF.CDEMPRESA    = P_CDEMPRESA
                                          AND NF.CDINSCESTA   = P_CDINSCESTA
                                          AND NF.IDENTRSAIDOP = 'S'
                                          AND NF.IDSTATUS     = 'C'
                                          AND NF.DTEMISSAO BETWEEN C_REG1700.DTINIPERIODO AND C_REG1700.DTFIMPERIODO
                                          AND LPAD(NF.NRNOTAFISC,12,'0') BETWEEN V_NOTA_ANT AND C_REG1700.NRNOTAFISC
                                        UNION ALL
                                        SELECT NU.NRINUTILNFELE AS NUM_DOC
                                          FROM NUMINUTILNFELE NU
                                         WHERE NU.CDEMPRESA  = P_CDEMPRESA
                                           AND NU.CDINSCESTA = P_CDINSCESTA
                                           AND NU.DTINUTNFE BETWEEN C_REG1700.DTINIPERIODO AND C_REG1700.DTFIMPERIODO
                                           AND LPAD(NU.NRINUTILNFELE,12,'0') BETWEEN V_NOTA_ANT AND C_REG1700.NRNOTAFISC
                                         ORDER BY 1)) LOOP
                   --REGISTRO 1710
                   V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
                  INSERT INTO ARQMAGNETICO
                     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                  VALUES
                     ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1710.ARQ_1710, P_NRSEQARQMAG);

               END LOOP;
            END IF;
            -- REGISTRO 1700
            V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), C_REG1700.ARQ_1700, P_NRSEQARQMAG);

            V_NOTA_ANT := C_REG1700.NRNOTAFISC;
         END LOOP;
      END IF;*/
	  BEGIN
         SELECT IDGERAJUST
           INTO V_IDGERAJUST
           FROM PARAMESTSPED
          WHERE CDEMPRESA = P_CDEMPRESA
            AND CDINSCESTA = P_CDINSCESTA;
	 EXCEPTION
	    WHEN NO_DATA_FOUND THEN
		   V_IDGERAJUST:= '';
	 END;

    IF V_IDUTSUBAPURCP = 'S' OR V_IDAPURLUCPRE = 'S' THEN
       BEGIN
          SELECT SUM(VRITEMMAPR)
            INTO V_DEB1900CP
            FROM ITMAPARECUP
           WHERE NRSEQUMAPAPU    = V_NRSEQUMAPAPU
             AND IDTIPOITMAPR    = 'ED'
             AND IDCREDPRESUMIDO = 'S';
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             V_DEB1900CP := 0;
       END;
       IF V_DEB1900CP > 0 THEN
          V_DSARQ1900 := '|1900'||'|'||V_IDINDICSUBAPURCP||'|'||V_DSOUTRAAPURCP||'|';
          V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
          INSERT INTO ARQMAGNETICO
             (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
          VALUES
             ('800'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

          V_DSARQ1900 := '|1910|'||TO_CHAR(P_DTINICIAL, 'DDMMYYYY')||'|'||TO_CHAR(P_DTFINAL, 'DDMMYYYY')||'|';
          V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
          INSERT INTO ARQMAGNETICO
             (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
          VALUES
             ('800'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

          FOR C_REG1921 IN (SELECT '|1921'          ||'|'||
                                   I.CDAJUSTEITMAPA ||'|'||
                                   I.DSITEMMAPR     ||'|'||
                                   I.VRITEMMAPR     ||'|' AS ARQ_1921, I.IDTIPOITMAPR, I.VRITEMMAPR
                              FROM ITMAPARECUP I
                             WHERE I.NRSEQUMAPAPU  = V_NRSEQUMAPAPU
                               AND I.IDAJSUBAPURCP = 'S') LOOP
             V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
             INSERT INTO ARQMAGNETICO
                (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
             VALUES
                ('801'||LPAD(RTRIM(V_CONTREG1), 7, '0'), C_REG1921.ARQ_1921, P_NRSEQARQMAG);

             CASE C_REG1921.IDTIPOITMAPR
                WHEN 'OC' THEN V_AJSUBAPUROC := NVL(V_AJSUBAPUROC,0) + C_REG1921.VRITEMMAPR;
                WHEN 'ED' THEN V_AJSUBAPURED := NVL(V_AJSUBAPURED,0) + C_REG1921.VRITEMMAPR;
                WHEN 'OD' THEN V_AJSUBAPUROD := NVL(V_AJSUBAPUROD,0) + C_REG1921.VRITEMMAPR;
                WHEN 'EC' THEN V_AJSUBAPUREC := NVL(V_AJSUBAPUREC,0) + C_REG1921.VRITEMMAPR;
                WHEN 'DD' THEN V_AJSUBAPURDD := NVL(V_AJSUBAPURDD,0) + C_REG1921.VRITEMMAPR;
                WHEN 'DE' THEN V_AJSUBAPURDE := NVL(V_AJSUBAPURDE,0) + C_REG1921.VRITEMMAPR;
             END CASE;
          END LOOP;

          V_TOTSUBAPUR := (NVL(V_DEB1900CP,0) + NVL(V_AJSUBAPUROD,0) + NVL(V_AJSUBAPUREC,0)) -
                          (NVL(V_AJSUBAPUROC,0) + NVL(V_AJSUBAPURED,0));

          V_DSARQ1900 := '|1920' ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_DEB1900CP,0),  '999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_AJSUBAPUROD,0),'999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_AJSUBAPUREC,0),'999999999990.00')), '.', ',') ||'|'||
                         '0,00'  ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_AJSUBAPUROC,0),'999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_AJSUBAPURED,0),'999999999990.00')), '.', ',') ||'|'||
                         '0,00'  ||'|'||
                         REPLACE(LTRIM(TO_CHAR(CASE WHEN NVL(V_TOTSUBAPUR,0) < 0 THEN 0 ELSE NVL(V_TOTSUBAPUR,0) END,'999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_AJSUBAPURDD,0),'999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(CASE WHEN NVL(V_TOTSUBAPUR,0) - NVL(V_AJSUBAPURDD,0) < 0 THEN 0
                                                    ELSE NVL(V_TOTSUBAPUR,0) - NVL(V_AJSUBAPURDD,0) END,'999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(CASE WHEN NVL(V_TOTSUBAPUR,0) - NVL(V_AJSUBAPURDD,0) >= 0 THEN 0
                                                    ELSE ABS(NVL(V_TOTSUBAPUR,0) - NVL(V_AJSUBAPURDD,0)) END,'999999999990.00')), '.', ',') ||'|'||
                         REPLACE(LTRIM(TO_CHAR(NVL(V_AJSUBAPURDE,0),'999999999990.00')), '.', ',') ||'|';

          V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
          INSERT INTO ARQMAGNETICO
             (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
          VALUES
             ('800'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

          FOR C_REG1926 IN (SELECT '|1926'           ||'|'||
                                   G.CDOBRIGAGUIA    ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(G.VRRECEITAGUIA,'999999999990.00')), '.', ',') ||'|'||
                                   TO_CHAR(DTVENCGUIACOMPL, 'DDMMYYYY') ||'|'||
                                   G.CDRECEITAGUIA   ||'|'||
                                   G.NRPROCESSOGUIA  ||'|'||
                                   CASE WHEN G.NRPROCESSOGUIA IS NULL THEN '' ELSE G.IDORIGEMGUIA END   ||'|'||
                                   G.DSHISTGUIACOMPL ||'|'||
                                   ''                ||'|'||
                                   TO_CHAR(P_DTINICIAL, 'MMYYYY') ||'|' AS ARQ_1926
                              FROM GUIACOMPLMAPA G
                             WHERE G.NRSEQUMAPAPU  = V_NRSEQUMAPAPU
                               AND G.IDGUIASUBAPUR = 'S') LOOP

             V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
             INSERT INTO ARQMAGNETICO
                (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
             VALUES
                ('801'||LPAD(RTRIM(V_CONTREG1), 7, '0'), C_REG1926.ARQ_1926, P_NRSEQARQMAG);
          END LOOP;
       END IF;
    END IF;

    IF V_IDGERAJUST = 'S' THEN
       BEGIN
           SELECT TPAPURACAO, CDAJUSTEENTRTRIB, CDAJUSTESAIDTRIB,
                  CDAJUSTEVRCOMPL, CDAJUSTEVRREST, VRALIQINTERNA
           INTO V_TPAPURACAO, V_CD1921ENTR, V_CD1921SAID,
                  V_CD1921COMPL, V_CD1921REST, V_ALIQINTERNA
             FROM PARAMESTSPED
            WHERE CDEMPRESA   = P_CDEMPRESA
              AND CDINSCESTA = P_CDINSCESTA;
        EXCEPTION
           WHEN NO_DATA_FOUND THEN
              V_TPAPURACAO  := '3';
              V_CD1921ENTR  := 'RS021922';
              V_CD1921SAID  := 'RS001920';
              V_CD1921COMPL := 'RS041921';
              V_CD1921REST  := 'RS011921';
             -- V_CDE220COMPL := 'RS101921';
             -- V_CDE220REST  := 'RS121921';
              V_ALIQINTERNA := 18;
        END;

        V_TPAPURACAO  := NVL(V_TPAPURACAO,'3');
        V_CD1921ENTR  := NVL(V_CD1921ENTR,'RS021922');
        V_CD1921SAID  := NVL(V_CD1921SAID,'RS001920');
        V_CD1921COMPL := NVL(V_CD1921COMPL,'RS041921');
        V_CD1921REST  := NVL(V_CD1921REST,'RS011921');
        --V_CDE220COMPL := NVL(V_CDE220COMPL,'RS101921');
        --V_CDE220REST  := NVL(V_CDE220REST,'RS121921');
        V_ALIQINTERNA := NVL(V_ALIQINTERNA,18);

	     FOR C_REG1923 IN (SELECT '|1923' ||'|'||
                                 'L'||FI.CDFILIAL ||'|'||
                                 '01'             ||'|'||
                                 '2D'             ||'|'||
                                 ''               ||'|'||
                                 LPAD(LTRIM(NVL(VE.NRCUPOMFIS,'0'),'0'), 9, '0') ||'|'||
                                 TO_CHAR(VE.DTENTRVENDA, 'DDMMYYYY') ||'|'||
                                 NVL(PE.CDARVPROD, PR.CDARVPROD)     ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(CASE WHEN ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) <= 0
                                                            THEN 0.01
                                                            ELSE ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) END,'999999999990.00')), '.', ',') ||'|'||
                                 ''               ||'|' AS ARQ_1923,
                                 'L'||FI.CDFILIAL AS COD_PART, NVL(VE.IDTPEMISVEND,'E') AS TIPO,
                                 PE.CDPRODUTO AS CDPRODESTO, PR.CDPRODUTO AS CDPRODUTO,
                                 MAX(IT.CDCLASFISC) AS CDCLASFISC, II.CDFILIAL,
                                 NVL(PE.CDARVPROD,PR.CDARVPROD) AS CDARVPROD,
                                 CASE WHEN ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) <= 0
                                      THEN 0.01
                                      ELSE ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) END AS VRSAIDA,
                                 SUM(ROUND(IT.QTPRODVEND*NVL(PR.VRFATOCONV,1),3)) AS QTDE, VE.DTENTRVENDA AS DATA
                            FROM ITVENDAIMPOS II, ITEMVENDA IT, VENDA VE, FILIAL FI, PRODUTO PR, PRODUTO PE
                           WHERE II.CDFILIAL     = IT.CDFILIAL
                             AND II.CDCAIXA      = IT.CDCAIXA
                             AND II.NRSEQVENDA   = IT.NRSEQVENDA
                             AND II.NRSEQUITVEND = IT.NRSEQUITVEND
                             AND II.CDFILIAL     = VE.CDFILIAL
                             AND II.CDCAIXA      = VE.CDCAIXA
                             AND II.NRSEQVENDA   = VE.NRSEQVENDA
                             AND VE.NRCUPOMFIS   IS NOT NULL
                             AND VE.IDSITUVENDA  = 'O'
                             AND FI.CDEMPRESA    = P_CDEMPRESA
                             AND FI.CDINSCESTA   = P_CDINSCESTA
                             AND VE.CDFILIAL     = FI.CDFILIAL
                             AND VE.DTENTRVENDA  BETWEEN P_DTINICIAL AND P_DTFINAL
                             AND II.CDCFOPPROD   = '5405'
                             AND NVL(VE.IDTPEMISVEND,'E') = 'E'
                             AND IT.CDPRODUTO    = PR.CDPRODUTO
                             AND PR.CDPRODESTO   = PE.CDPRODUTO(+)
                           GROUP BY FI.CDFILIAL, LPAD(LTRIM(NVL(VE.NRCUPOMFIS,'0'),'0'), 9, '0'),
                                 TO_CHAR(VE.DTENTRVENDA, 'DDMMYYYY'), NVL(PE.CDARVPROD, PR.CDARVPROD),
                                 NVL(VE.IDTPEMISVEND,'E'), PE.CDPRODUTO, PR.CDPRODUTO,
                                 II.CDFILIAL, VE.DTENTRVENDA
                           UNION ALL
                          SELECT '|1923' ||'|'||
                                 ''               ||'|'||
                                 '65'             ||'|'||
                                 VE.CDSERIENFCE   ||'|'||
                                 ''               ||'|'||
                                 LPAD(LTRIM(NVL(VE.NRNOTAFISCALCE,'0'),'0'), 9, '0') ||'|'||
                                 TO_CHAR(VE.DTEMISSAONFCE, 'DDMMYYYY') ||'|'||
                                 NVL(PE.CDARVPROD, PR.CDARVPROD)       ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(CASE WHEN ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) <= 0
                                                            THEN 0.01
                                                            ELSE ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) END,'999999999990.00')), '.', ',') ||'|'||
                                 VE.NRACESSONFCE   ||'|' AS ARQ_1923,
                                 '' AS COD_PART, VE.IDTPEMISVEND AS TIPO,
                                 PE.CDPRODUTO AS CDPRODESTO, PR.CDPRODUTO AS CDPRODUTO,
                                 MAX(IT.CDCLASFISC) AS CDCLASFISC, VE.CDFILIAL,
                                 NVL(PE.CDARVPROD,PR.CDARVPROD) AS CDARVPROD,
                                 CASE WHEN ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) <= 0
                                      THEN 0.01
                                      ELSE ROUND(SUM(TRUNC(IT.QTPRODVEND*(NVL(IT.VRUNITVEND,0)+NVL(IT.VRUNITVENDCL,0))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) * V_ALIQINTERNA/100,2) END AS VRSAIDA,
                                 SUM(ROUND(IT.QTPRODVEND*NVL(PR.VRFATOCONV,1),3)) AS QTDE, TRUNC(VE.DTEMISSAONFCE) AS DATA
                            FROM ITVENDAIMPOS II, ITEMVENDA IT,  VENDA VE, FILIAL FI, PRODUTO PR, PRODUTO PE
                           WHERE FI.CDEMPRESA       = P_CDEMPRESA
                             AND FI.CDINSCESTA      = P_CDINSCESTA
                             AND FI.CDEMPRESA       = VE.CDEMPRESA
                             AND FI.CDFILIAL        = VE.CDFILIAL
                             AND TRUNC(VE.DTEMISSAONFCE) BETWEEN P_DTINICIAL AND P_DTFINAL
                             AND VE.IDSITUVENDA     = 'O'
                             AND VE.IDTPAMBNFCE     = '1'
                             AND VE.IDSTATUSNFCE    = 'A'
                             AND VE.CDFILIAL        = IT.CDFILIAL
                             AND VE.NRSEQVENDA      = IT.NRSEQVENDA
                             AND VE.CDCAIXA         = IT.CDCAIXA
                             AND IT.CDFILIAL        = II.CDFILIAL
                             AND IT.CDCAIXA         = II.CDCAIXA
                             AND IT.NRSEQUITVEND    = II.NRSEQUITVEND
                             AND IT.NRSEQVENDA      = II.NRSEQVENDA
                             AND II.CDCFOPPROD      = '5405'
                             AND VE.IDAPROVACAONFCE = 'A'
                             AND VE.IDTPEMISVEND    = 'N'
                             AND IT.CDPRODUTO       = PR.CDPRODUTO
                             AND PR.CDPRODESTO      = PE.CDPRODUTO(+)
                           GROUP BY VE.CDSERIENFCE , LPAD(LTRIM(NVL(VE.NRNOTAFISCALCE,'0'),'0'), 9, '0'),
                                 TO_CHAR(VE.DTEMISSAONFCE, 'DDMMYYYY'), NVL(PE.CDARVPROD, PR.CDARVPROD),
                                 VE.NRACESSONFCE, VE.IDTPEMISVEND, PE.CDPRODUTO, PR.CDPRODUTO,
                                 VE.CDFILIAL, TRUNC(VE.DTEMISSAONFCE)) LOOP

            V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('8011'||LPAD(RTRIM(V_CONTREG1), 6, '0'), C_REG1923.ARQ_1923, P_NRSEQARQMAG);

            V_AJUSTEDEB := NVL(V_AJUSTEDEB,0) + C_REG1923.VRSAIDA;

             if C_REG1923.CDARVPROD is not null then
               V_CDPRODUTO := C_REG1923.CDARVPROD;
            end if;

            SELECT MAX(CDCHAVEREG)
              INTO V_COD_PAR
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REG1923.COD_PART
               AND CDREGISTRO = '0150';

            IF (V_COD_PAR IS NULL) AND (C_REG1923.COD_PART IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0150', V_SEQUPROD, C_REG1923.COD_PART);
            END IF;

            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REG1923.CDPRODESTO
               AND CDREGISTRO = '0200';

            IF (V_PRODUTO IS NULL) AND (C_REG1923.CDPRODESTO IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
               VALUES
                  ('0200', V_SEQUPROD, C_REG1923.CDPRODESTO, C_REG1923.CDCLASFISC);
            END IF;

            FOR C_REG1923E IN (SELECT '|1923'             ||'|'||
                                      'L'||N.CDFILIRECE   ||'|'||
                                      N.CDMODDOCFISC      ||'|'||
                                      N.CDSERIEENTR       ||'|'||
                                      ''                  ||'|'||
                                      LPAD(LTRIM(NVL(N.NRNOTAFISC,'0'),'0'), 9, '0') ||'|'||
                                      TO_CHAR(N.DTENTRSAID, 'DDMMYYYY') ||'|'||
                                      C_REG1923.CDARVPROD ||'|'||
                                      REPLACE(LTRIM(TO_CHAR(ROUND(N.VRST *(C_REG1923.QTDE*NVL(N.VRFATCONV,1))/ N.QTITEMPROD,2),'999999999990.00')), '.', ',') ||'|'||
                                      N.NRACESSONFE     ||'|' AS ARQ_1923,
                                      ROUND(N.VRST * (C_REG1923.QTDE*NVL(N.VRFATCONV,1)) / N.QTITEMPROD,2) AS VALOR,
                                      'L'||N.CDFILIRECE AS COD_PART
                                 FROM ENTRADAREF N
                                WHERE N.CDPRODUTO  = C_REG1923.CDPRODUTO
                                  AND N.CDFILIRECE = C_REG1923.CDFILIAL
                                  AND N.DTVENDA    = C_REG1923.DATA) LOOP

            V_AJUSTECRED := NVL(V_AJUSTECRED,0) + C_REG1923E.VALOR;

            if C_REG1923E.COD_PART is not null then
               V_CDFILIAL  := C_REG1923E.COD_PART;
              end if;

            V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('8021'||LPAD(RTRIM(V_CONTREG1), 6, '0'), C_REG1923E.ARQ_1923, P_NRSEQARQMAG);

             SELECT MAX(CDCHAVEREG)
              INTO V_COD_PAR
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REG1923E.COD_PART
               AND CDREGISTRO = '0150';

            IF (V_COD_PAR IS NULL) AND (C_REG1923E.COD_PART IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0150', V_SEQUPROD, C_REG1923E.COD_PART);
            END IF;
           END LOOP;
	     END LOOP;

        IF NVL(V_AJUSTEDEB,0) > NVL(V_AJUSTECRED,0) THEN
           V_RESTITUIR := 0;
           V_COMPLEMENTAR  := NVL(V_AJUSTEDEB,0) - NVL(V_AJUSTECRED,0);
        ELSE
           V_RESTITUIR := NVL(V_AJUSTECRED,0) - NVL(V_AJUSTEDEB,0);
           V_COMPLEMENTAR  := 0;
        END IF;

        V_SALDOAPUR := NVL(V_AJUSTEDEB,0) + NVL(V_RESTITUIR,0) - NVL(V_AJUSTECRED,0);

		IF (NVL(V_AJUSTECRED,0) > 0) OR (NVL(V_AJUSTEDEB,0) > 0) THEN
			V_DSARQ1900 := '|1900'||'|'||V_TPAPURACAO||'|'||'AJUSTE DO MONTANTE DO IMPOSTO A (RICMS, Livro III, arts. 25-A a 25-C)'||'|';
			V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			INSERT INTO ARQMAGNETICO
			   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			   ('800'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			V_DSARQ1900 := '|1910|'||TO_CHAR(P_DTINICIAL, 'DDMMYYYY')||'|'||TO_CHAR(P_DTFINAL, 'DDMMYYYY')||'|';
			V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			INSERT INTO ARQMAGNETICO
			   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			   ('800'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			V_DSARQ1900 := '|1920'      ||'|'|| /*Registro*/
                        '0,00'       ||'|'|| /*Debitos por Saidas e prestacoes com debito do imposto*/
                        REPLACE(LTRIM(TO_CHAR(NVL(V_AJUSTEDEB,0),'999999999990.00')), '.', ',')  ||'|'|| /*Ajustes a debito*/
                        REPLACE(LTRIM(TO_CHAR(NVL(V_RESTITUIR,0),'999999999990.00')), '.', ',')  ||'|'|| /*Estorno de credito*/
                        '0,00'       ||'|'|| /*Entradas e aquisicoes com credito do imposto*/
                        REPLACE(LTRIM(TO_CHAR(NVL(V_AJUSTECRED,0),'999999999990.00')), '.', ',') ||'|'|| /*Ajustes a credito*/
                        '0,00'       ||'|'|| /*Estornos de Debitos*/
                        '0,00'       ||'|'|| /*Saldo credor do periodo anterior*/
                        REPLACE(LTRIM(TO_CHAR(NVL(V_SALDOAPUR,0),'999999999990.00')), '.', ',')  ||'|'|| /*Saldo devedor apurado*/
                        REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0),'999999999990.00')), '.', ',')  ||'|'|| /*Deducoes*/
                        '0,00'       ||'|'|| /*ICMS a recolher*/
                        '0,00'       ||'|'|| /*Saldo credor a transportar para o periodo seguinte*/
                        '0,00'       ||'|'; /*Valores recolhidos ou a recolher, extraapuracao*/

			V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			INSERT INTO ARQMAGNETICO
			   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			   ('800'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			/*Valores referentes as Saidas para Consumidor Final com Substituicao Tributaria*/
			V_DSARQ1900 := '|1921|'||V_CD1921SAID||'||'||REPLACE(LTRIM(TO_CHAR(NVL(V_AJUSTEDEB,0), '999999999990.00')), '.', ',')||'|';
			V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			INSERT INTO ARQMAGNETICO
			   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			   ('8010'||LPAD(RTRIM(V_CONTREG1), 6, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			/*Valores referentes a Proporcao das Saidas nas Entradas para Consumidor Final com Substituicao Tributaria*/
			V_DSARQ1900 := '|1921|'||V_CD1921ENTR||'||'||REPLACE(LTRIM(TO_CHAR(NVL(V_AJUSTECRED,0), '999999999990.00')), '.', ',')||'|';
			V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			INSERT INTO ARQMAGNETICO
			   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			   ('8020'||LPAD(RTRIM(V_CONTREG1), 6, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			/*REGISTRO E200 - ICMS ST*/
			/*SELECT '|E200'                         || '|' ||
				   IE.SGESTADO                     || '|' ||
				   TO_CHAR(P_DTINICIAL,'DDMMYYYY') || '|' ||
				   TO_CHAR(P_DTFINAL,'DDMMYYYY')   || '|'   AS ARQ_E200
			  INTO V_REG_E220
			  FROM INSCRESTAD IE
			 WHERE IE.CDEMPRESA    = P_CDEMPRESA
			   AND IE.CDINSCESTA   = P_CDINSCESTA;

			V_CONTREGE := NVL(V_CONTREGE,0) + 1;
			INSERT INTO ARQMAGNETICO
			  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			  ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'1', V_REG_E220, P_NRSEQARQMAG);

			V_REG_E220 := '|E210'                          ||'|'||
						  '0'                              ||'|'|| --INDICADOR DE MOVIMENTO(CAMPO 2)
						  '0,00'                           ||'|'|| --SALDO CREDOR PERIDODO ANTERIOR ST(CAMPO 3)
						  '0,00'                           ||'|'|| --SALDO CREDOR DE DEVOLUO(CAMPO 4)
						  '0,00'                           ||'|'|| --VALOR DE RESSARCIMENTO(CAMPO 5)
						  REPLACE(LTRIM(TO_CHAR(NVL(V_RESTITUIR,0),'999999999990.00')),'.',',')     ||'|'|| --VALOR DE OUT. CRED. + EST. DEB(CAMPO 6)
						  '0,00'                           ||'|'|| --AJUSTE A CREDITO ST DOC. FISCAL(CAMPO 7)
						  '0,00'                           ||'|'|| --VALOR RETENO ST (CAMPO 8)
						  REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0),'999999999990.00')),'.',',')  ||'|'|| --VALOR DE OUT. DEB. + ESTORNO CRED. (CAMPO 9)
						  '0,00'                           ||'|'|| --VALOR AJUSTE A DEB. DOC. FISC(CAMPO 10)
						  REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0),'999999999990.00')),'.',',')  ||'|'|| --VALOR SALDO DEB ANT. DEDUES(CAMPO 11)
						  '0,00'                           ||'|'|| --VALOR DA DEDUCAO(CAMPO 12)
						  REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0),'999999999990.00')),'.',',')  ||'|'|| --VALOR IMP. RECOLHER (CAMPO 13)
						  REPLACE(LTRIM(TO_CHAR(NVL(V_RESTITUIR,0),'999999999990.00')),'.',',')     ||'|'|| --VALOR SALDO CREDOR(CAMPO 14)
						  '0,00'                           ||'|';  --VALOR EXTRA APURA??O(CAMPO 15)

			INSERTE O REGISTRO E210
			V_CONTREGE := NVL(V_CONTREGE,0) + 1;
			INSERT INTO ARQMAGNETICO
			   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			VALUES
			   ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'2',V_REG_E220, P_NRSEQARQMAG);*/

			IF V_RESTITUIR > 0 THEN
			   /*V_REG_E220 := '|E220'      || '|' ||
							 V_CDE220REST || '|' ||
							 'Valor a restituir, Ajuste do Montante do Imposto (RICMS, Livro III, arts. 25-A a 25-C)' || '|' ||
							 REPLACE(LTRIM(TO_CHAR(NVL(V_RESTITUIR,0), '999999999990.00')), '.', ',') || '|';
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'3', V_REG_E220, P_NRSEQARQMAG);
			   V_CONTREGE := NVL(V_CONTREGE,0) + 1;*/

			   /*Valor referente ao montante a ser restituido*/
			   V_DSARQ1900 := '|1921|'||V_CD1921REST||'||'||REPLACE(LTRIM(TO_CHAR(NVL(V_RESTITUIR,0), '999999999990.00')), '.', ',')||'|';
			   V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('803'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			   /*Gera o registro 1923 com o totalizador*/
			   BEGIN
               SELECT '|1923'      ||'|'||
                      V_CDFILIAL   ||'|'||
                      '01'         ||'|'||
                      ''           ||'|'||
                      ''           ||'|'||
                      SUBSTR(M.NRSEQUMAPAPU,2,9) ||'|'||
                      TO_CHAR(M.DTFIMPERIODO, 'DDMMYYYY') ||'|'||
                      V_CDPRODUTO  ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(V_RESTITUIR,0), '999999999990.00')), '.', ',') ||'|'||
                      ''           ||'|' AS ARQ_1923
                  INTO V_DSARQ1900
                  FROM MAPAAPURAC M
                 WHERE M.NRSEQUMAPAPU = V_NRSEQUMAPAPU;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_DSARQ1900 := '';
            END;

			   V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('803'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);
			END IF;

			IF V_COMPLEMENTAR > 0 THEN
			   /*V_REG_E220 :=   '|E220'       || '|' ||
							   V_CDE220COMPL || '|' ||
							   'Valor a complementar, Ajuste do Montante do Imposto (RICMS, Livro III, arts. 25-A a 25-C)' || '|' ||
							   REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0), '999999999990.00')), '.', ',') || '|';
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'3', V_REG_E220, P_NRSEQARQMAG);
			   V_CONTREGE := NVL(V_CONTREGE,0) + 1;

			   V_REG_E220 := '|E250'     || '|' ||
							 '002'       || '|' ||
							 REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0), '999999999990.00')), '.', ',') || '|' ||
							 '20'||TO_CHAR(ADD_MONTHS(P_DTFINAL,1),'MMYYYY') || '|' ||
							 '1224'      || '|' ||
							 ''          || '|' ||
							 ''          || '|' ||
							 ''          || '|' ||
							 ''          || '|' ||
							 TO_CHAR(P_DTFINAL,'MMYYYY') || '|';
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('56'||LPAD(RTRIM(V_CONTREGE), 7, '0')||'3', V_REG_E220, P_NRSEQARQMAG);
			   V_CONTREGE := NVL(V_CONTREGE,0) + 1;*/

			   /*Valor referente ao montante a ser complementado*/
			   V_DSARQ1900 := '|1921|'||V_CD1921COMPL||'||'||REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0), '999999999990.00')), '.', ',')||'|';
			   V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('803'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);

			   /*Gera o registro 1923 com o totalizador*/
			   BEGIN
               SELECT '|1923'        ||'|'||
                      V_CDFILIAL     ||'|'||
                      '01'           ||'|'||
                      ''             ||'|'||
                      ''             ||'|'||
                      SUBSTR(M.NRSEQUMAPAPU,2,9) ||'|'||
                      TO_CHAR(M.DTFIMPERIODO, 'DDMMYYYY') ||'|'||
                      V_CDPRODUTO    ||'|'||
                      REPLACE(LTRIM(TO_CHAR(NVL(V_COMPLEMENTAR,0), '999999999990.00')), '.', ',') ||'|'||
                      ''             ||'|' AS ARQ_1923
                  INTO V_DSARQ1900
                  FROM MAPAAPURAC M
                 WHERE M.NRSEQUMAPAPU = V_NRSEQUMAPAPU;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_DSARQ1900 := '';
            END;
			   V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
			   INSERT INTO ARQMAGNETICO
				  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
			   VALUES
				  ('803'||LPAD(RTRIM(V_CONTREG1), 7, '0'), V_DSARQ1900, P_NRSEQARQMAG);
			END IF;
		END IF;
	  END IF;

   ELSE
      /* ABERTURA DO BLOCO 1 */
      V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
      INSERT INTO ARQMAGNETICO
        (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
        ('80'||LPAD(RTRIM(V_CONTREG1), 8, '0'), '|1001'|| '|' ||'1'|| '|', P_NRSEQARQMAG);
   END IF;

   /* ENCERRAMENTO DO BLOCO 1 */
   V_CONTREG1 := NVL(V_CONTREG1,0) + 1;
   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('81'||LPAD(RTRIM(V_CONTREG1), 8, '0'), '|1990'|| '|' ||V_CONTREG1|| '|' , P_NRSEQARQMAG);

   RETURN(V_CONTREG1);
END;
/