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;
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)
        INTO V_CDPAIS, V_SGESTADO, V_CDMUNIEXPO
        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_SGESTADO := NULL;
   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,3,1) || '|' || /*REGISTRO 1300*/
                       SUBSTR(P_OBRIGREGBL1,4,1) || '|' || /*REGISTRO 1390*/
                       SUBSTR(P_OBRIGREGBL1,5,1) || '|' || /*REGISTRO 1400*/
                       SUBSTR(P_OBRIGREGBL1,6,1) || '|' || /*REGISTRO 1500*/
                       SUBSTR(P_OBRIGREGBL1,7,1) || '|' || /*REGISTRO 1600*/
                       SUBSTR(P_OBRIGREGBL1,8,1) || '|' || /*REGISTRO 1700*/
                       SUBSTR(P_OBRIGREGBL1,9,1) || '|' || /*REGISTRO 1800*/
                       CASE WHEN P_VERSAO >= '013' THEN
                          SUBSTR(P_OBRIGREGBL1,10,1) || '|' || /*REGISTRO 1960*/
                          SUBSTR(P_OBRIGREGBL1,11,1) || '|' || /*REGISTRO 1970*/
                          SUBSTR(P_OBRIGREGBL1,12,1) || '|'    /*REGISTRO 1980*/
                       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,5,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
            /*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(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0)) 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(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0)), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(NVL(DECODE(IDENTRSAIDOP,'S',VRCONTABILNF,0),0) - NVL(DECODE(IDENTRSAIDOP,'E',VRCONTABILNF,0),0)) 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 nao por Produto como nos demais estados */
            FOR C_REG1400 IN (SELECT '|1400'      || '|' ||
                                     'SPDIPAM11'  || '|' ||
                                     NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(SUM(I.VRCONTABILNF), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(VRCONTABILNF) 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 e o valor de rateio por municipio;
                -SVM e o valor total das saidas por municipio;
                -SVC e o 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(IP.VRCONTABILNF),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(IP.VRCONTABILNF),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(IT.VRCONTITIMP), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(VRCONTITIMP) AS VALOR
                                FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO PR,
                                     (SELECT N.CDFILIAL, N.NRLANCTONF, NVL(M.CDMUNICIBGE, M.CDMUNICIPIO) AS CDMUNICIBGE, SUM(I.VRCONTABILNF)
                                        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(I.VRCONTABILNF)
                                        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(I.VRCONTABILNF)
                                        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(IT.VRCONTITIMP), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(VRCONTITIMP) 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(I.VRCONTABILNF)
                                        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(IT.VRCONTITIMP), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                     SUM(VRCONTITIMP) 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(I.VRCONTABILNF)
                                        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 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(I.VRCONTABILNF)
                                        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 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(I.VRCONTABILNF)
                                        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 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,5,1) = 'S') AND (V_CDSITUCRT = '1') THEN  /*SIMPLES NACIONAL*/
         FOR C_REG1400 IN (SELECT '|1400'                                                                   || '|' ||
                                  PR.CDARVPROD                                                              || '|' ||
                                  NF.CDMUNICIBGE                                                            || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(SUM(IT.VRCONTITIMP), '999999999990.00')), '.', ',') || '|' AS ARQ_1400,
                                  SUM(VRCONTITIMP) 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(I.VRCONTABILNF)
                                     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(I.VRCONTABILNF)
                                     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(I.VRCONTABILNF)
                                     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 SUBSTR(P_OBRIGREGBL1,7,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;
      /*IF SUBSTR(P_OBRIGREGBL1,8,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;*/

   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;