CREATE OR REPLACE FUNCTION SPED_PIS_COFINS_BLOCO0(
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_NRSEQARQMAG  IN ARQMAGPISCOFINS.NRSEQARQMAG%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_VERSAO       IN VARCHAR2,
   P_TPESCRITU    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_IDSITUESP    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_NUMRECANT    IN VARCHAR2,
   P_TPNATJURPJ   IN NOTAFISCAL.CDMODDOCFISC%TYPE,
   P_ATIVIDADE    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_CDINCTRIB    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_INDAPROCRED  IN NOTAFISCAL.IDSTATUS%TYPE,
   P_CDTPCON      IN NOTAFISCAL.IDSTATUS%TYPE,
   P_CRTESCRITUR  IN NOTAFISCAL.IDSTATUS%TYPE,
   P_LIVROMAG     IN RELACPRODITGEN.CDLIVROMAG%TYPE,
   P_GERABCLP     IN VARCHAR2,
   P_CDPAIS       IN PAIS.CDPAIS%TYPE,
   P_ICMS         IN IMPOSTO.CDIMPOSTO%TYPE,
   P_IPI          IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_E        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_S        IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_RET_E    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ISS_RET_S    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS          IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS_RET_E    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_PIS_RET_S    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS       IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS_RET_E IN IMPOSTO.CDIMPOSTO%TYPE,
   P_COFINS_RET_S IN IMPOSTO.CDIMPOSTO%TYPE,
   P_ICMS_ST      IN IMPOSTO.CDIMPOSTO%TYPE,
   P_NATUJURID    IN VARCHAR2,
   P_IDFORAPER    IN NOTAFISCAL.IDSTATUS%TYPE,
   P_IDCONSPRODEXT IN NOTAFISCAL.IDSTATUS%TYPE) RETURN NUMBER
AS
   V_REG_0000       VARCHAR2(1000);
   V_REG_0110       VARCHAR2(1000);
   V_REG_0140       VARCHAR2(1000);
   V_REG_A001       VARCHAR2(100);
   V_REG_C001       VARCHAR2(100);
   V_REG_D001       VARCHAR2(100);
   V_REG_M001       VARCHAR2(100);
   V_REG_F001       VARCHAR2(100);
   V_REG_P001       VARCHAR2(100);
   V_CNPJ_0140      VARCHAR2(20);
   V_INSJUREST      VARCHAR2(20);
   V_OLDESTAB       VARCHAR2(20);
   V_CONTEST        NUMBER;
   V_NEWESTAB       NUMBER;
   V_TOTLINHAS      NUMBER;
   V_TOTBLC0        NUMBER;
   V_TOTBLCA        NUMBER;
   V_TOTBLCC        NUMBER;
   V_TOTBLCD        NUMBER;
   V_TOTBLCM        NUMBER;
   V_TOTBLCP        NUMBER;
   V_TOTBLC1        NUMBER;
   V_SEQNOTAS       NUMBER;
   V_SEQESTAB       NUMBER;
   V_CONTREGA       NUMBER;
   V_IDNOVOESTA     VARCHAR2(1);
   V_IDNOVOESTC     VARCHAR2(1);
   V_IDNOVOESTD     VARCHAR2(1);
   VDIMPISS         VARCHAR2(2);
   VDIMPICMS        VARCHAR2(2);
   V_SGESTEMPR      VARCHAR2(2);
   V_CDPAISEMPR     VARCHAR2(4);
   V_CDMUNIEMPR     VARCHAR2(4);
   V_PRODUTO        VARCHAR(100);
   V_UNID           VARCHAR(4);
   TIPOOPER_COMPL_S VARCHAR2(2);
   TIPOOPER_COMPL_E VARCHAR2(2);
   V_RESULTADO      VARCHAR2(100);
   IDGEROUBCLACD    VARCHAR2(1);
   V_REG            VARCHAR2(1000);
   V_SEQA           NUMBER;
   V_SEQC           NUMBER;
   V_SEQD           NUMBER;
   V_SEQ1           NUMBER;
   V_TMPBLCM        NUMBER;
   V_TOTALBCLF      NUMBER;
   V_SEQESTABBLCF   NUMBER;
   V_IDOUTROS       VARCHAR2(1);
   V_VRDESTOTIT     FLOAT;
   V_VROUTDESPIT    FLOAT;
   V_FRETE          FLOAT;
   V_DESCONTO       FLOAT;
   V_OUTROS         FLOAT;
   V_SEGUR          FLOAT;
   V_COUNTBL0ECF    NUMBER;
   V_COUNTBL0P      NUMBER;
   V_COUNTBL01      NUMBER;
   V_CNPJ_REAL      VARCHAR2(20);
   V_CONTREG1       NUMBER;
   V_SEMMOVIMENTO   VARCHAR2(1);
   V_SEQVENDAS      NUMBER;
   V_GERADEVOLVEND  VARCHAR2(1);
   V_NRSEQUMAPPIS   VARCHAR2(10);
   V_COD_CC         VARCHAR2(20);
   V_SEQCCTBL       NUMBER;
   V_CONTBLC0M      NUMBER;
   V_IDGERANFESTDD  VARCHAR2(01);
   V_CONTCTBL_SPED  VARCHAR2(20);
   V_SEQADIC        NUMBER;
   V_IDUTCDEXTPRONF VARCHAR2(01);
BEGIN
   DELETE FROM TMP_REGDADOSSPED_NF_AUX;
   DELETE FROM TMP_REGDADOSSPED_NF;
   DELETE FROM TMP_REGDADOSSPED_ECF_NF;
   DELETE FROM TMP_REGDADOSSPED_ECF_RE;

   V_TMPBLCM := 0;
   V_SEQESTAB:= 0;
   V_SEQADIC := 0;
   V_CONTCTBL_SPED := null;

   BEGIN
      SELECT CDPAIS,SGESTADO, CDMUNICIPIO
        INTO V_CDPAISEMPR, V_SGESTEMPR, V_CDMUNIEMPR
        FROM EMPRESA
       WHERE CDEMPRESA = P_CDEMPRESA;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDPAISEMPR:= '55';
         V_SGESTEMPR:= 'MG';
         V_CDMUNIEMPR:= '0001';
   END;

   BEGIN
      SELECT MAX(IDDEVOLNCUMUSPED), MAX(IDGERANFESTDD)
        INTO V_GERADEVOLVEND, V_IDGERANFESTDD
        FROM PARAMFISCAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
        V_GERADEVOLVEND := 'A';
        V_IDGERANFESTDD := 'N';
   END;

   /*SELECTIONA O TIPO DE OPERACAO DE NOTAS FISCAIS COMPLEMENTARES QUE SEJAM DIFERENTES DE 03. TIPO DE OPERACAO 03 JA E FIXO NO SISTEMA COM COMPLEMENTAR*/
   SELECT MAX(TIPOOPER_S), MAX(TIPOOPER_E)
     INTO TIPOOPER_COMPL_S, TIPOOPER_COMPL_E
     FROM (SELECT DECODE(IDENTRSAIDOP,'S',CDTIPOOPER,NULL) AS TIPOOPER_S,
                  DECODE(IDENTRSAIDOP,'E',CDTIPOOPER,NULL) AS TIPOOPER_E
             FROM TIPOOPERAC
            WHERE UPPER(NMTIPOOPER) LIKE '%NF COMPLEMENTO%'
              AND CDTIPOOPER <> '03');

   /*REGISTRO 0000*/
   BEGIN
      SELECT '|0000'                         ||'|'||
             P_VERSAO                        ||'|'||
             P_TPESCRITU                     ||'|'||
             P_IDSITUESP                     ||'|'||
             P_NUMRECANT                     ||'|'||
             TO_CHAR(P_DTINICIAL,'ddmmyyyy') ||'|'||
             TO_CHAR(P_DTFINAL,'ddmmyyyy')   ||'|'||
             NMRAZSOCEMPR                    ||'|'||
             NRINSJUREMPR                    ||'|'||
             E.SGESTADO                      ||'|'||
             M.CDMUNICIBGE                   ||'|'||
             ''                              ||'|'||
             P_NATUJURID                     ||'|'||
             P_ATIVIDADE                     ||'|'
        INTO V_REG_0000
        FROM EMPRESA E, MUNICIPIO M
       WHERE E.CDPAIS      = M.CDPAIS
         AND E.SGESTADO    = M.SGESTADO
         AND E.CDMUNICIPIO = M.CDMUNICIPIO
         AND E.CDEMPRESA   = P_CDEMPRESA;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_REG_0000 := '';
   END;

   V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,LPAD('0',10,'0'),V_REG_0000);

   /*REGISTRO 0001*/
   V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'101'||LPAD('0',7,'0'),'|0001|0|');

   /* GERACAO DO REGISTRO 0035 SOMENTE PARA AS NATUREZAS JURIDIAS 03 E 04 */
   IF P_NATUJURID IN ('03', '04') THEN
      FOR C_0035 IN (SELECT '|0035' ||'|'||
                            REPLACE(REPLACE(REPLACE(CODSCP,'-',''),'/',''),'.','') ||'|'||
                            DESCSCP ||'|'||
                            INFCOMP ||'|' AS REGISTRO
                       FROM SCPEMPRESA
                      WHERE CDEMPRESA = P_CDEMPRESA) LOOP

         V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
         V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
         INSERT INTO ARQMAGPISCOFINS
           (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
           (P_NRSEQARQMAG,'101'||LPAD('0',8,'0'),C_0035.REGISTRO);
      END LOOP;
   END IF;

   /*Registro 0100*/
   FOR REG_0100 IN(SELECT ('|0100'                                  || '|' ||
                          NMCONTADOR                                || '|' ||
                          NRCPFRESPONS                              || '|' ||
                          REPLACE(REPLACE(NRCRCCONT2,'/',''),'-','')|| '|' ||
                          ''                                        || '|' ||
                          REPLACE(REPLACE(NRCEP,'/',''),'-','')     || '|' ||
                          LTRIM(RTRIM(DSLOGRADOURO))                || '|' ||
                          ''                                        || '|' ||
                          LTRIM(RTRIM(DSCOMPLLOGRA))                || '|' ||
                          LTRIM(RTRIM(DSBAIRRO))                    || '|' ||
                          SUBSTR(RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(NRTELCONTATO, '(',''),')','') ,'-',''))),1,10)  || '|' ||
                          SUBSTR(RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(NRFAXCONTATO, '(',''),')','') ,'-',''))),1,10)  || '|' ||
                          DSENDINTERN                               || '|' ||
                          M.CDMUNICIBGE                             || '|'  ) ARQ_0100
                     FROM CONTADOR C, MUNICIPIO M, EMPRESA E
                    WHERE E.CDCONTADOR2 = C.CDCONTADOR2
                      AND C.CDPAIS      = M.CDPAIS
                      AND C.CDMUNICIPIO = M.CDMUNICIPIO
                      AND C.SGESTADO    = M.SGESTADO
                      AND E.CDEMPRESA   = P_CDEMPRESA)LOOP

      V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
      V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'102'||LPAD(RTRIM(V_TOTLINHAS),27,'0'),REG_0100.ARQ_0100);
   END LOOP;

   /*REGISTRO 0110*/
   V_REG_0110 := '|0110'        ||'|'||
                 P_CDINCTRIB    ||'|'||
                 P_INDAPROCRED  ||'|'||
                 P_CDTPCON      ||'|';

   /*Campo criterio da escrituracao a ser importado pelo PVA*/
   IF P_VERSAO NOT IN ('001','002') THEN
      IF P_CDINCTRIB = '2' THEN
         V_REG_0110:= V_REG_0110||P_CRTESCRITUR||'|';
      ELSE
         V_REG_0110:= V_REG_0110||'|';
      END IF;
   END IF;

   V_TOTBLC0   := NVL(V_TOTBLC0,  0)+1;
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'103'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),V_REG_0110);

    /*SELECT QUE BUSCA AS NOTAS QUE IRAO COMPOR O ARQUIVO - PRINCIPAL*/
   FOR C_NOTAS IN (SELECT NRLANCTONF, CDFILIAL, ESTAB
                     FROM (SELECT DISTINCT NF.NRLANCTONF, NF.CDFILIAL,
                                  BUSCA_CNPJ_ESTAB(P_ICMS,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,NF.NRLANCTONF,NF.CDFILIAL,NF.CDINSCESTA,NF.CDINSCMUNI,NF.CDFILIEMIT,NF.CDFILIRECE,NF.IDENTRSAIDOP) AS ESTAB
                             FROM NOTAFISCAL NF, TIPOOPERAC TP, FILIAL F, CFOPPADRAO C, ITEMPROIMPOS IT,(SELECT IP.CDFILIAL, IP.NRLANCTONF, IP.CDFISCOPERNF
                                                                                           FROM MAPAAPURAC MP, IMPOSTONF IP, IMPOSTO IM
                                                                                          WHERE MP.CDEMPRESA    = P_CDEMPRESA
                                                                                            AND MP.CDIMPOSTO    IN (P_PIS,P_COFINS)
                                                                                            AND MP.DTINIPERIODO = P_DTINICIAL
                                                                                            AND MP.DTFIMPERIODO = P_DTFINAL
                                                                                            AND MP.NRSEQUMAPAPU = IP.NRSEQUMAPAPU
                                                                                            AND MP.CDIMPOSTO    = IM.CDIMPOSTONFE
                                                                                            AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                                                                                          UNION ALL
                                                                                         SELECT IB.CDFILIAL, IB.NRLANCTONF, IB.CDFISCOPERNF
                                                                                           FROM MAPAAPURAC MP, IMPBAIXAREC IB, IMPOSTO IM
                                                                                          WHERE MP.CDEMPRESA    = P_CDEMPRESA
                                                                                            AND MP.CDIMPOSTO    IN (P_PIS,P_COFINS)
                                                                                            AND MP.DTINIPERIODO = P_DTINICIAL
                                                                                            AND MP.DTFIMPERIODO = P_DTFINAL
                                                                                            AND MP.NRSEQUMAPAPU = IB.NRSEQUMAPAPU
                                                                                            AND MP.CDIMPOSTO    = IM.CDIMPOSTONFE
                                                                                            AND IM.CDIMPOSTO    = IB.CDIMPOSTO) IP
                            WHERE IP.CDFILIAL     = NF.CDFILIAL
                              AND IP.NRLANCTONF   = NF.NRLANCTONF
                              AND NF.IDSTATUS IN ('A','E')
                              AND NF.IDENTRSAIDOP = 'E'
                              AND NF.CDFILIRECE = F.CDFILIAL
                              AND F.IDCUMUPISCOFIL = 'S'
                              AND IP.CDFISCOPERNF   = C.CDCFOPPADRAO(+)
                              AND ((NVL(C.IDTIPOCFOP,'X') <> 'D') OR ((IP.CDFISCOPERNF  = C.CDCFOPPADRAO) AND                                                                     
									                                  (C.IDTIPOCFOP     = 'D') AND
									                                  (NVL(V_GERADEVOLVEND,'A') = 'C')))
                              AND NF.IDENTRSAIDOP = TP.IDENTRSAIDOP
                              AND NF.CDTIPOOPER   = TP.CDTIPOOPER
                              AND ((TP.IDNFESTCANC = 'N') OR (TP.IDNFESTCANC = 'S' AND V_IDGERANFESTDD = 'N'))
                              AND IT.CDFILIAL = IP.CDFILIAL
                              AND IT.NRLANCTONF = IP.NRLANCTONF
                              AND IT.CDSITUTRIBITNFE IN ('50', '51', '52', '53', '54', '55', '56','60', '61','62', '63', '64','65', '66')
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'REC'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'PAG'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'CMP'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'SUP'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'FIS'
                              --AND NVL(NF.IDSISTEMA, 'DFS') <> 'TMP' /*As notas do TMP devem entrar no arquivo para quem utiliza regime de caixa e o ForSale*/
            
                             UNION ALL
                             
                             SELECT DISTINCT NF.NRLANCTONF, NF.CDFILIAL,
                                  BUSCA_CNPJ_ESTAB(P_ICMS,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,NF.NRLANCTONF,NF.CDFILIAL,NF.CDINSCESTA,NF.CDINSCMUNI,NF.CDFILIEMIT,NF.CDFILIRECE,NF.IDENTRSAIDOP) AS ESTAB
                             FROM NOTAFISCAL NF, TIPOOPERAC TP, FILIAL F, CFOPPADRAO C, (SELECT IP.CDFILIAL, IP.NRLANCTONF, IP.CDFISCOPERNF
                                                                                           FROM MAPAAPURAC MP, IMPOSTONF IP, IMPOSTO IM
                                                                                          WHERE MP.CDEMPRESA    = P_CDEMPRESA
                                                                                            AND MP.CDIMPOSTO    IN (P_PIS,P_COFINS)
                                                                                            AND MP.DTINIPERIODO = P_DTINICIAL
                                                                                            AND MP.DTFIMPERIODO = P_DTFINAL
                                                                                            AND MP.NRSEQUMAPAPU = IP.NRSEQUMAPAPU
                                                                                            AND MP.CDIMPOSTO    = IM.CDIMPOSTONFE
                                                                                            AND IM.CDIMPOSTO    = IP.CDIMPOSTO
                                                                                          UNION ALL
                                                                                         SELECT IB.CDFILIAL, IB.NRLANCTONF, IB.CDFISCOPERNF
                                                                                           FROM MAPAAPURAC MP, IMPBAIXAREC IB, IMPOSTO IM
                                                                                          WHERE MP.CDEMPRESA    = P_CDEMPRESA
                                                                                            AND MP.CDIMPOSTO    IN (P_PIS,P_COFINS)
                                                                                            AND MP.DTINIPERIODO = P_DTINICIAL
                                                                                            AND MP.DTFIMPERIODO = P_DTFINAL
                                                                                            AND MP.NRSEQUMAPAPU = IB.NRSEQUMAPAPU
                                                                                            AND MP.CDIMPOSTO    = IM.CDIMPOSTONFE
                                                                                            AND IM.CDIMPOSTO    = IB.CDIMPOSTO) IP
                            WHERE IP.CDFILIAL     = NF.CDFILIAL
                              AND IP.NRLANCTONF   = NF.NRLANCTONF
                              AND NF.IDSTATUS IN ('A','E')
                              AND NF.IDENTRSAIDOP = 'S'
                              AND NF.CDFILIEMIT = F.CDFILIAL
                              AND F.IDCUMUPISCOFIL IN ('S','N')
                              AND IP.CDFISCOPERNF   = C.CDCFOPPADRAO(+)
                              AND NVL(C.IDTIPOCFOP,'X') <> 'D'
                              AND NF.IDENTRSAIDOP = TP.IDENTRSAIDOP
                              AND NF.CDTIPOOPER   = TP.CDTIPOOPER
                              AND ((TP.IDNFESTCANC = 'N') OR (TP.IDNFESTCANC = 'S' AND V_IDGERANFESTDD = 'N'))
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'REC'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'PAG'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'CMP'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'SUP'
                              AND NVL(NF.IDSISTEMA, 'DFS')  <> 'FIS'
                              ))LOOP

         /*GRAVA TODAS A NOTAS QUE ESTAO NO ARQUIVO*/
         V_SEQNOTAS := NVL(V_SEQNOTAS,0) + 1;
         INSERT INTO TMP_REGDADOSSPED_PIS
            (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2, CDESTAB)
         VALUES
            ('NOTA', V_SEQNOTAS, C_NOTAS.CDFILIAL||C_NOTAS.NRLANCTONF, C_NOTAS.CDFILIAL, C_NOTAS.NRLANCTONF, C_NOTAS.ESTAB);
   END LOOP;

   /*SELECT QUE BUSCA AS NOTAS FISCAIS ELETRONICAS AO CONSUMIDOR FINAL (NFC-e) QUE IRAO COMPOR O ARQUIVO - PRINCIPAL*/
   FOR C_VENDAS IN (SELECT NRSEQVENDA, CDFILIAL, CDCAIXA,
                           LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(NRINSJURFILI,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0')||'ICM' AS ESTAB,
                           IDTPEMISVEND
                      FROM (SELECT DISTINCT VE.NRSEQVENDA, VE.CDFILIAL, VE.CDCAIXA, FI.NRINSJURFILI, VE.IDTPEMISVEND
                              FROM VENDA VE, FILIAL FI, MAPAAPURAC MP, RELACNFCEAPROV RE, NOTAFISCAL NF
                             WHERE MP.CDEMPRESA       = P_CDEMPRESA
                               AND MP.CDIMPOSTO       IN (P_PIS,P_COFINS)
                               AND MP.DTINIPERIODO    = P_DTINICIAL
                               AND MP.DTFIMPERIODO    = P_DTFINAL
                               AND FI.CDEMPRESA       = MP.CDEMPRESA
                               AND FI.CDFILIAL        = VE.CDFILIAL
                               AND RE.CDFILIALVENDA   = VE.CDFILIAL
                               AND RE.CDCAIXA         = VE.CDCAIXA
                               AND RE.NRSEQVENDA      = VE.NRSEQVENDA
                               AND RE.CDFILIALNOTA    = NF.CDFILIAL
                               AND RE.NRLANCTONF      = NF.NRLANCTONF
                               AND NF.DTEMISSAO       BETWEEN MP.DTINIPERIODO AND MP.DTFIMPERIODO
                               AND VE.IDSITUVENDA     = 'O'
                               AND VE.IDTPAMBNFCE     = '1'
                               AND VE.IDSTATUSNFCE    IN ('A','C')
                               AND VE.IDAPROVACAONFCE = 'A'
                               AND VE.IDTPEMISVEND    IN ('N','S')))LOOP

         /*GRAVA TODAS A NFC-E's QUE ESTAO NO ARQUIVO*/
         V_SEQVENDAS := NVL(V_SEQVENDAS,0) + 1;
         INSERT INTO TMP_REGDADOSSPED_PIS
            (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2, CDCAMPO3, CDESTAB)
         VALUES
            (DECODE(C_VENDAS.IDTPEMISVEND, 'N', 'NFCE', 'SAT'), V_SEQVENDAS, C_VENDAS.CDFILIAL||C_VENDAS.NRSEQVENDA||C_VENDAS.CDCAIXA, C_VENDAS.CDFILIAL, C_VENDAS.NRSEQVENDA, C_VENDAS.CDCAIXA, C_VENDAS.ESTAB);
   END LOOP;

   V_SEMMOVIMENTO := 'S';
   V_CONTEST      := NULL;
   IF P_GERABCLP IN ('0','1') THEN
      IF (NVL(P_CRTESCRITUR,'9') = '9') THEN /*ESCRITURACAO DETALHADA*/
         /*Preenche as tabelas temporarias para identificar a conta contabil nos registros de venda, evitando que a rotina seja realizada a todo momento*/
         DELETE FROM TMP_REGDADOSSPED_NF_AUX;
         INSERT INTO TMP_REGDADOSSPED_NF_AUX
            (IDENTRSAIDOP, CDTIPOOPER, CDFILIAL)
         (SELECT 'S' AS IDENTRSAIDOP, PV.CDTPOPERCNTREC AS CDTIPOOPER, VE.CDFILIAL
            FROM TMP_REGDADOSSPED_PIS TMP, VENDA VE, ITEMVENDA IT, FILIAL FI, PARAVEND PV
           WHERE TMP.CDREGISTRO = 'NFCE'
             AND TMP.CDCAMPO1   = VE.CDFILIAL
             AND TMP.CDCAMPO2   = VE.NRSEQVENDA
             AND TMP.CDCAMPO3   = VE.CDCAIXA
             AND VE.CDFILIAL    = IT.CDFILIAL
             AND VE.NRSEQVENDA  = IT.NRSEQVENDA
             AND VE.CDCAIXA     = IT.CDCAIXA
             AND VE.CDFILIAL    = FI.CDFILIAL
             AND VE.CDFILIAL    = PV.CDFILIAL
             AND PV.CDFILIAL    = FI.CDFILIAL);

         DELETE FROM TMP_REGDADOSSPED_NF;
         INSERT INTO TMP_REGDADOSSPED_NF
            (IDENTRSAIDOP, CDTIPOOPER, CDFILIAL, CONTCTBL)
         (SELECT DISTINCT IDENTRSAIDOP, CDTIPOOPER, CDFILIAL, NULL CONTCTBL
            FROM TMP_REGDADOSSPED_NF_AUX);

         UPDATE TMP_REGDADOSSPED_NF
            SET CONTCTBL = CONTCTBL_SPED(IDENTRSAIDOP, '', CDTIPOOPER, CDFILIAL);

         /*BUSCA AS NOTAS PARA GERAR O ARQUIVO DE FORMA DETALHADA - BLOCOS A,C,D,F*/
         FOR C_NOTAS_DETAL IN (SELECT CDREGISTRO, NRLANCTONF, CDFILIAL, '' AS CDCAIXA, IDENTRSAIDOP,IDSTATUS,CDINSCESTA, CDINSCMUNI,
                                      CDFORNECED, CDCLIENTE, CDFILIEMIT, CDFILIRECE, CDSERIE, CDSERIEENTR, NRNOTAFISC,
                                      DTEMISSAO, DTENTRSAID, NRACESSONFE, VRNOTAFISC, VRPRODUTOS,
                                      VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF, '50','C') AS VRCONTABIL,
                                      IDPGTOFRETE, CDMODDOCFISC, SUBSTR(CDESTAB,1,LENGTH(CDESTAB)-3) AS CNPJ,
                                      SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3) AS IDIMPOSTO,
                                      CDTIPOOPER, IDSTATUSNFE, NRNOTAFISCALELE,
                                      NVL(IDORIGDESTNF, CASE WHEN CDFORNECED IS NOT NULL THEN 'F'
                                                             WHEN CDCLIENTE  IS NOT NULL THEN 'C'
                                                             WHEN CDFORNECED IS NULL AND CDCLIENTE IS NULL THEN 'L' END) AS IDORIGDESTNF,
                                      NF.CDTIPOCTE,
                                      NF.IDNATFRETECTE
                                 FROM TMP_REGDADOSSPED_PIS TMP, NOTAFISCAL NF
                                WHERE TMP.CDREGISTRO = 'NOTA'
                                  AND TMP.CDCAMPO1   = NF.CDFILIAL
                                  AND TMP.CDCAMPO2   = NF.NRLANCTONF
                                UNION ALL
                               SELECT TMP.CDREGISTRO, VE.NRSEQVENDA AS NRLANCTONF, VE.CDFILIAL, VE.CDCAIXA, 'S' AS IDENTRSAIDOP, VE.IDSTATUSNFCE AS IDSTATUS,
                                      FI.CDINSCESTA AS CDINSCESTA, FI.CDINSCMUNI AS CDINSCMUNI, '' AS CDFORNECED, '' AS CDCLIENTE, '' AS CDFILIEMIT, '' AS CDFILIRECE,
                                      VE.CDSERIENFCE AS CDSERIE, '' AS CDSERIEENTR, VE.NRNOTAFISCALCE AS NRNOTAFISC,
                                      TRUNC(VE.DTEMISSAONFCE) AS  DTEMISSAO, TRUNC(VE.DTEMISSAONFCE) AS DTENTRSAID, VE.NRACESSONFCE AS NRACESSONFE,
                                      SUM(TRUNC((IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VRNOTAFISC,
                                      SUM(TRUNC((IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VRPRODUTOS,
                                      SUM(TRUNC((IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)))-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0),2)) AS VRCONTABIL,
                                      '9' AS IDPGTOFRETE, '65' AS CDMODDOCFISC, SUBSTR(CDESTAB,1,LENGTH(CDESTAB)-3) AS CNPJ, SUBSTR(CDESTAB,LENGTH(CDESTAB)-2,3) AS IDIMPOSTO,
                                      PV.CDTPOPERCNTREC AS CDTIPOOPER, VE.IDSTATUSNFCE AS IDSTATUSNFE,
                                      VE.NRNOTAFISCALCE AS NRNOTAFISCALELE, 'C' AS IDORIGDESTNF, '' AS CDTIPOCTE,'' AS IDNATFRETECTE
                                 FROM TMP_REGDADOSSPED_PIS TMP, VENDA VE, ITEMVENDA IT, FILIAL FI, PARAVEND PV
                                WHERE TMP.CDREGISTRO = 'NFCE'
                                  AND TMP.CDCAMPO1   = VE.CDFILIAL
                                  AND TMP.CDCAMPO2   = VE.NRSEQVENDA
                                  AND TMP.CDCAMPO3   = VE.CDCAIXA
                                  AND TMP.CDCAMPO1   = IT.CDFILIAL
                                  AND TMP.CDCAMPO2   = IT.NRSEQVENDA
                                  AND TMP.CDCAMPO3   = IT.CDCAIXA
                                  AND TMP.CDCAMPO1   = FI.CDFILIAL
                                  AND TMP.CDCAMPO1   = PV.CDFILIAL
                                  AND VE.CDFILIAL    = IT.CDFILIAL
                                  AND VE.NRSEQVENDA  = IT.NRSEQVENDA
                                  AND VE.CDCAIXA     = IT.CDCAIXA
                                  AND VE.CDFILIAL    = FI.CDFILIAL
                                  AND VE.CDFILIAL    = PV.CDFILIAL
                                  AND PV.CDFILIAL    = FI.CDFILIAL
                                  AND IT.CDFILIAL    = FI.CDFILIAL
                                  AND PV.CDFILIAL    = IT.CDFILIAL
                                GROUP BY TMP.CDREGISTRO, VE.NRSEQVENDA, VE.CDFILIAL, VE.CDCAIXA, VE.IDSTATUSNFCE, FI.CDINSCESTA, FI.CDINSCMUNI,
                                         VE.CDSERIENFCE, VE.NRNOTAFISCALCE, TRUNC(VE.DTEMISSAONFCE), VE.DTENTRVENDA, VE.NRACESSONFCE,
                                         TMP.CDESTAB, PV.CDTPOPERCNTREC
                                ) LOOP

            IF C_NOTAS_DETAL.CDREGISTRO = 'NOTA' THEN
               /*BUSCA O VALOR DOS ENCARGOS*/
               /*PEGA O VALOR DO FRETE*/
               BEGIN
                  SELECT SUM(VRITEMENCA)
                    INTO V_FRETE
                    FROM ITEMENCARGO I, ENCARGO EN
                   WHERE I.CDENCARGO     = EN.CDENCARGO
                     AND EN.CDENCARGONFE = '01'
                     AND NRLANCTONF      = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL        = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_FRETE:=0;
               END;

               /*PEGA O VALOR DO SEGURO*/
               BEGIN
                  SELECT SUM(VRITEMENCA)
                    INTO V_SEGUR
                    FROM ITEMENCARGO I, ENCARGO EN
                   WHERE I.CDENCARGO     = EN.CDENCARGO
                     AND EN.CDENCARGONFE = '02'
                     AND NRLANCTONF      = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL        = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_SEGUR:=0;
               END;

               /*PEGA O VALOR DO DESCONTO*/
               BEGIN
                  SELECT SUM(VRDESCITEM)
                    INTO V_DESCONTO
                    FROM ITEMPRODUTO
                   WHERE NRLANCTONF = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL   = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_DESCONTO:=0;
               END;

               /*PEGA O VALOR DE OUTROS*/
               BEGIN
                  SELECT SUM(VRITEMENCA)
                    INTO V_OUTROS
                    FROM ITEMENCARGO I, ENCARGO EN
                   WHERE I.CDENCARGO     = EN.CDENCARGO
                     AND EN.CDENCARGONFE = '04'
                     AND NRLANCTONF      = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL        = C_NOTAS_DETAL.CDFILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_OUTROS:=0;
               END;
            ELSE /*NFC-e*/
               /*BUSCA O VALOR DOS ENCARGOS*/
               V_FRETE :=0;
               V_SEGUR :=0;
               V_OUTROS:=0;
               V_INSJUREST := NULL;
               /*PEGA O VALOR DO DESCONTO*/
               BEGIN
                  SELECT SUM(VRDESITVEND)
                    INTO V_DESCONTO
                    FROM ITEMVENDA
                   WHERE NRSEQVENDA = C_NOTAS_DETAL.NRLANCTONF
                     AND CDFILIAL   = C_NOTAS_DETAL.CDFILIAL
                     AND CDCAIXA    = C_NOTAS_DETAL.CDCAIXA;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_DESCONTO:=0;
               END;
            END IF;

            /*VERIFICA SE CONSIDERA CODIGO EXTERNO DO PRODUTO NA GERACAO DO ARQUIVO*/
            V_IDUTCDEXTPRONF := 'N';
            IF P_IDCONSPRODEXT = 'S' THEN
               BEGIN
                  SELECT NVL(IDUTCDEXTPRONF,'N')
                    INTO V_IDUTCDEXTPRONF
                    FROM PARAMFILIAL
                   WHERE ((CDFILIAL = C_NOTAS_DETAL.CDFILIRECE AND C_NOTAS_DETAL.IDENTRSAIDOP =  'E')
                            OR (CDFILIAL = C_NOTAS_DETAL.CDFILIEMIT AND C_NOTAS_DETAL.IDENTRSAIDOP =  'S'));
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDUTCDEXTPRONF:='N';
               END;
             END IF;

            /*ALTERADO----VERIFICA CNPJ A SER INSERIDO*/
            SELECT MAX(LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0'))
              INTO V_CNPJ_REAL
              FROM INSCRESTAD I
             WHERE I.CDEMPRESA  = P_CDEMPRESA
               AND I.CDINSCESTA = C_NOTAS_DETAL.CDINSCESTA;

            /*VERIFICA SE O ESTABELECIMENTO JA FOI INSERIDO*/
            V_INSJUREST:= NULL;
            SELECT MAX(CDCHAVEREG),MAX(CDESTAB)
              INTO V_INSJUREST, V_OLDESTAB
              FROM TMP_REGDADOSSPED_PIS TMP
             WHERE CDREGISTRO = '0140'
               AND CDCHAVEREG = V_CNPJ_REAL;

            /*LEMBRAR QUE O REGISTRO 0140 TAMBEM  INSERIDO NA FUNCAO SPED_PIS_COFINS_BLOCOC_ECF*/
            /*GERA O REGISTRO 0140 - ESTABELECIMENTO*/
            IF V_INSJUREST IS NULL THEN
               /*ACRESCE UM NO NUMERO DO ESTABELECIMENTO*/
               V_CONTEST:= NVL(V_CONTEST,0)+1;
               V_NEWESTAB:= V_CONTEST;
               BEGIN
                  SELECT REG, INSJUREST
                    INTO V_REG, V_INSJUREST
                    FROM (SELECT '|0140'         ||'|'||
                                 LTRIM(TO_CHAR(V_NEWESTAB,'000'))      ||'|'||
                                 E.NMRAZSOCEMPR  ||'|'||
                                 LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') ||'|'||
                                 I.SGESTADO     ||'|'||
                                 ''/*REPLACE(REPLACE(REPLACE(REPLACE(IE.CDINSCESTA,'.',''),'/',''),'-',''),'\','')*/ ||'|'||
                                 M.CDMUNICIBGE   ||'|'||
                                 ''             ||'|'||
                                 ''             ||'|' AS REG,
                                 LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') AS INSJUREST
                            FROM MUNICIPIO M, INSCRESTAD I, EMPRESA E
                           WHERE I.CDEMPRESA    = P_CDEMPRESA
                             AND I.CDINSCESTA   = C_NOTAS_DETAL.CDINSCESTA
                             AND I.CDPAIS       = M.CDPAIS
                             AND I.SGESTADO     = M.SGESTADO
                             AND I.CDMUNICIPIO  = M.CDMUNICIPIO
                             AND E.CDEMPRESA    = I.CDEMPRESA);
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_REG:= C_NOTAS_DETAL.CDINSCESTA||'-'||C_NOTAS_DETAL.NRLANCTONF||'-'||C_NOTAS_DETAL.CDFILIAL;
                     V_INSJUREST:='';
               END;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG);

               V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
               V_CONTREGA:= NVL(V_CONTREGA,0)+1;
               V_TOTBLC0:= NVL(V_TOTBLC0,0)+1;

               INSERT INTO TMP_REGDADOSSPED_PIS
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                VALUES
                 ('0140', V_SEQESTAB, V_INSJUREST ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000')));
            ELSE
               V_NEWESTAB:= TO_NUMBER(V_OLDESTAB);
            END IF;

            /*VARIAVEL IDENTIFICA SE GEROU O BLOCO A,C,E -  SE NAO GERAR GERA PELO BLOCO F */
            IDGEROUBCLACD:= 'N';

            IF C_NOTAS_DETAL.IDIMPOSTO = 'ICM' THEN
               IF C_NOTAS_DETAL.CDMODDOCFISC IN ('01','1B','04','55','02','06','29','28','65','66') THEN

                   BEGIN
                     SELECT CONTCTBL
                       INTO V_CONTCTBL_SPED
                       FROM TMP_REGDADOSSPED_NF
                      WHERE IDENTRSAIDOP = C_NOTAS_DETAL.IDENTRSAIDOP
                        AND CDTIPOOPER   = C_NOTAS_DETAL.CDTIPOOPER
                        AND CDFILIAL     = C_NOTAS_DETAL.CDFILIAL;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                       V_CONTCTBL_SPED:=NULL;
                  END;

                  /*BLOCO C*/  --C_NOTAS_DETAL.IDENTRSAIDOP, C_NOTAS_DETAL.CDTIPOOPER, C_NOTAS_DETAL.CDFILIAL
                  V_RESULTADO:= NVL(SPED_PIS_COFINS_BLOCOC(C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.CDFILIAL, C_NOTAS_DETAL.CDCAIXA,
                                                           P_NRSEQARQMAG,V_INSJUREST,V_IDNOVOESTC,
                                                           C_NOTAS_DETAL.IDENTRSAIDOP,C_NOTAS_DETAL.IDSTATUS,
                                                           C_NOTAS_DETAL.IDORIGDESTNF,C_NOTAS_DETAL.CDFILIEMIT,
                                                           C_NOTAS_DETAL.CDFILIRECE,C_NOTAS_DETAL.CDCLIENTE,
                                                           C_NOTAS_DETAL.CDFORNECED,NVL(C_NOTAS_DETAL.CDSERIE, C_NOTAS_DETAL.CDSERIEENTR),
                                                           C_NOTAS_DETAL.NRNOTAFISC,C_NOTAS_DETAL.DTEMISSAO,C_NOTAS_DETAL.DTENTRSAID,
                                                           C_NOTAS_DETAL.VRNOTAFISC,C_NOTAS_DETAL.VRCONTABIL, P_PIS,P_PIS_RET_E,P_PIS_RET_S,
                                                           P_COFINS,P_COFINS_RET_E,P_COFINS_RET_S,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,
                                                           V_NEWESTAB,P_CDPAIS, P_CDEMPRESA,NVL(V_SEQC,0),C_NOTAS_DETAL.IDPGTOFRETE,
                                                           C_NOTAS_DETAL.NRACESSONFE, C_NOTAS_DETAL.CDMODDOCFISC,C_NOTAS_DETAL.VRPRODUTOS,
                                                           P_ICMS_ST,P_IPI,P_ICMS,P_DTINICIAL,P_DTFINAL,V_DESCONTO,C_NOTAS_DETAL.CDTIPOOPER,
                                                           C_NOTAS_DETAL.IDSTATUSNFE, V_FRETE,V_OUTROS,V_SEGUR,TIPOOPER_COMPL_S,
                                                           TIPOOPER_COMPL_E,V_SEQESTAB,V_TMPBLCM,C_NOTAS_DETAL.NRNOTAFISCALELE,
                                                           P_LIVROMAG,V_GERADEVOLVEND,P_VERSAO,V_CONTCTBL_SPED,V_SEQADIC,V_IDUTCDEXTPRONF),0);
                  V_TOTBLCC  := TO_NUMBER(SUBSTR(V_RESULTADO,1,20));
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + TO_NUMBER(SUBSTR(V_RESULTADO,22,20));
                  V_TMPBLCM  := NVL(V_TMPBLCM, 0) + TO_NUMBER(SUBSTR(V_RESULTADO,43,20));
                  V_SEQC     := NVL(V_TOTBLCC, 0);
                  V_SEQADIC  := TO_NUMBER(SUBSTR(V_RESULTADO,64,20));
                  IDGEROUBCLACD:= 'S';
               END IF;
            END IF;

            /*GERA BLOCO A*/
            IF C_NOTAS_DETAL.IDIMPOSTO = 'ISS' THEN
               V_RESULTADO:= NVL(SPED_PIS_COFINS_BLOCOA(C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.CDFILIAL,
                                                        P_NRSEQARQMAG,V_INSJUREST,V_IDNOVOESTA,
                                                        C_NOTAS_DETAL.IDENTRSAIDOP,C_NOTAS_DETAL.CDTIPOOPER,
                                                        C_NOTAS_DETAL.IDSTATUS, C_NOTAS_DETAL.IDORIGDESTNF,
                                                        C_NOTAS_DETAL.CDFILIEMIT,C_NOTAS_DETAL.CDFILIRECE,
                                                        C_NOTAS_DETAL.CDCLIENTE,C_NOTAS_DETAL.CDFORNECED,
                                                        NVL(C_NOTAS_DETAL.CDSERIE, C_NOTAS_DETAL.CDSERIEENTR),
                                                        C_NOTAS_DETAL.NRNOTAFISC,C_NOTAS_DETAL.DTEMISSAO,C_NOTAS_DETAL.DTENTRSAID,
                                                        C_NOTAS_DETAL.VRNOTAFISC,P_PIS,P_PIS_RET_E,P_PIS_RET_S,P_COFINS,P_COFINS_RET_E,P_COFINS_RET_S,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,V_NEWESTAB,P_CDPAIS,
                                                        P_CDEMPRESA,NVL(V_SEQA,0),V_VRDESTOTIT,V_SEQESTAB,V_TMPBLCM,P_LIVROMAG,V_SEQADIC,V_IDUTCDEXTPRONF),0);
               V_TOTBLCA  := TO_NUMBER(SUBSTR(V_RESULTADO,1,20));
               V_SEQA     := NVL(V_TOTBLCA, 0);
               V_SEQESTAB := NVL(V_SEQESTAB,0) + TO_NUMBER(SUBSTR(V_RESULTADO,22,20));
               V_TMPBLCM  := NVL(V_TMPBLCM, 0) + TO_NUMBER(SUBSTR(V_RESULTADO,43,20));
               V_SEQADIC  := TO_NUMBER(SUBSTR(V_RESULTADO,64,20));
               IDGEROUBCLACD:= 'S';
            END IF;

            IF C_NOTAS_DETAL.CDMODDOCFISC IN ('07','08','09','10','11','26','27','57','67','21','22')  AND C_NOTAS_DETAL.IDENTRSAIDOP = 'E' AND C_NOTAS_DETAL.IDIMPOSTO = 'ICM' THEN
               /*GERA BLOCO D*/
               V_RESULTADO:= NVL(SPED_PIS_COFINS_BLOCOD(C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.CDFILIAL,
                                                        P_NRSEQARQMAG,V_INSJUREST,V_IDNOVOESTD,
                                                        C_NOTAS_DETAL.IDENTRSAIDOP,C_NOTAS_DETAL.CDTIPOOPER,
                                                        C_NOTAS_DETAL.IDSTATUS, C_NOTAS_DETAL.IDORIGDESTNF,C_NOTAS_DETAL.IDNATFRETECTE,
                                                        C_NOTAS_DETAL.CDFILIEMIT, C_NOTAS_DETAL.CDFILIRECE,
                                                        C_NOTAS_DETAL.CDCLIENTE, C_NOTAS_DETAL.CDFORNECED,
                                                        NVL(C_NOTAS_DETAL.CDSERIE, C_NOTAS_DETAL.CDSERIEENTR),
                                                        C_NOTAS_DETAL.NRNOTAFISC,C_NOTAS_DETAL.DTEMISSAO,C_NOTAS_DETAL.DTENTRSAID,
                                                        C_NOTAS_DETAL.VRNOTAFISC,P_PIS,P_PIS_RET_E,P_PIS_RET_S,P_COFINS,P_COFINS_RET_E,
                                                        P_COFINS_RET_S,P_ISS_E,P_ISS_S,P_ISS_RET_E,P_ISS_RET_S,V_NEWESTAB,P_CDPAIS,
                                                        P_CDEMPRESA,NVL(V_SEQD,0),P_ICMS,P_DTFINAL,P_DTINICIAL,C_NOTAS_DETAL.CDMODDOCFISC,
                                                        V_VRDESTOTIT,V_IDOUTROS,V_SEQESTAB,V_TMPBLCM,C_NOTAS_DETAL.NRACESSONFE,
                                                        C_NOTAS_DETAL.CDTIPOCTE, C_NOTAS_DETAL.IDSTATUSNFE,V_SEQADIC),0);
               V_TOTBLCD  := TO_NUMBER(SUBSTR(V_RESULTADO,1,20));
               V_SEQD     := NVL(V_TOTBLCD, 0);
               V_SEQESTAB := NVL(V_SEQESTAB,0) + TO_NUMBER(SUBSTR(V_RESULTADO,22,20));
               V_TMPBLCM  := NVL(V_TMPBLCM, 0) + TO_NUMBER(SUBSTR(V_RESULTADO,43,20));
               V_SEQADIC  := TO_NUMBER(SUBSTR(V_RESULTADO,64,20));
               IDGEROUBCLACD:= 'S';
               /*V_IDNOVOESTD:= 'N';*/
            END IF;

            /*VEFIFICA SE A NOTA FOI GERADA NOS BLOCOS A, C OU D. CASO NAO TENHA SIDO GERADA INSERE O LANCAMENTO PARA GERAR PELO BLOCO F*/
            IF IDGEROUBCLACD = 'N' THEN
               --V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
               INSERT INTO TMP_REGDADOSSPED_PIS
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDCAMPO2, CDCAMPO3, CDESTAB)
               VALUES
                  ('F100', V_SEQESTAB, C_NOTAS_DETAL.CDFILIAL||C_NOTAS_DETAL.NRLANCTONF,C_NOTAS_DETAL.CDFILIAL,C_NOTAS_DETAL.NRLANCTONF, C_NOTAS_DETAL.IDIMPOSTO,'0000');
            END IF;

            V_SEMMOVIMENTO := 'N';
         END LOOP;/*END C_NOTAS_DETAL*/

   ---------------------------------------   /*GERA O REGISTRO C380 - NOTAS FISCAIS MODELO 02*/------------------------------------------------------------
         FOR C_REGC380 IN (SELECT '|C380'                                   ||'|'||
                                  '02'                                      ||'|'||
                                  TO_CHAR(DTEMISSAO,'ddmmyyyy')             ||'|'||
                                  TO_CHAR(DTEMISSAO,'ddmmyyyy')             ||'|'||
                                  SUBSTR(LPAD(MIN(MIN_NUM_DOC),10,'0'),5,6) ||'|'||
                                  SUBSTR(LPAD(MIN(MAX_NUM_DOC),10,'0'),5,6) ||'|'||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(SUM(VRNOTAFISC),2), '999999999990.00')), '.', ',')       || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(ROUND(SUM(CANC_VRNOTAFISC),2), '999999999990.00')), '.', ',')  || '|' AS C380,
                                  ESTABELECIMENTO,DTEMISSAO, MAX(CDFILIEMIT) AS CDFILIEMIT,NRINSJUREST
                             FROM (SELECT SUM(CDCAMPO8) AS VRNOTAFISC, DECODE(CDCAMPO3,'C',SUM(CDCAMPO8),0) AS CANC_VRNOTAFISC,
                                          MIN(CDCAMPO6) AS  MIN_NUM_DOC, MAX(CDCAMPO6) AS MAX_NUM_DOC,
                                          TO_DATE(CDCAMPO1) AS DTEMISSAO, CDESTAB AS ESTABELECIMENTO, MAX(CDCAMPO7) AS CDFILIEMIT,NRINSJUREST
                                     FROM TMP_REGDADOSSPED_PIS
                                    WHERE CDREGISTRO = 'C380'
                                    GROUP BY CDCAMPO1,CDCAMPO3,CDESTAB,NRINSJUREST)
                            GROUP BY DTEMISSAO,ESTABELECIMENTO,NRINSJUREST)LOOP
            V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'))||'02'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),C_REGC380.C380);
            V_SEQC:= NVL(V_SEQC,0)+1;

            /*REGISTRO C381*/
            FOR REGC381 IN (SELECT '|C381'                  ||'|'||
                                   CDSITUTRIBITNFE          ||'|'||
                                   CDARVPROD                ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRTOTAITEM),'9999999999900.00')),'.',',') ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRBASECALCIT),'9999999999900.00')),'.',',')||'|'||
                                   REPLACE(LTRIM(TO_CHAR(VRALIQITEM,'9900.0000')),'.',',')||'|'||
                                   ''                                                                                    ||'|'||
                                   ''                                                                                    ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRIMPOSTOIT),'9999999999900.00')),'.',',')||'|'||
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT) ||'|'/*CODIGO DA CONTA ANALITICA*/ AS C381,
                                   CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE, CDNATUREC, SUM(VRTOTAITEM) AS VRTOTAITEM,
                                   SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,VRALIQITEM, MAX(CDFILIEMIT) AS CDFILIEMIT,
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT) AS COD_CTA, IDUTCDEXTPRONF, CDARVORIG
                              FROM (SELECT ROUND(IP.VRTOTAITEM,2) AS VRTOTAITEM,
                                           IT.CDTPCREDPICOITE,
                                           DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_PIS,'B','1'),0) AS VRBASECALCIT,
                                           ROUND(IT.VRALIQITEM,4) AS VRALIQITEM,
                                           ROUND(DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_PIS,'I','1'),0),2) AS VRIMPOSTOIT,
                                           IT.CDNATUBCALPCIT,
                                           IT.CDSITUTRIBITNFE,
                                           DECODE(TMP.CDCAMPO10,'S',NVL(P.CDPRODINTE,P.CDARVPROD),P.CDARVPROD) AS CDARVPROD,
                                           P.SGUNIDADE,
                                           IT.CDFISCALIT,
                                           NVL(IT.CDNATUREC,R.CDNATUREC) AS CDNATUREC,
                                           TMP.CDCAMPO7 AS CDFILIEMIT,
                                           P.CDPRODUTO,                          
                                           TMP.CDCAMPO9 AS CDTIPOOPER,
                                           TMP.CDCAMPO10 AS IDUTCDEXTPRONF, P.CDARVPROD AS CDARVORIG
                                      FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO P, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R
                                     WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                       AND IM.CDIMPOSTONFE = P_PIS
                                       AND IT.NRLANCTONF   = IP.NRLANCTONF
                                       AND IT.CDFILIAL     = IP.CDFILIAL
                                       AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                       AND IT.NRITPROIMPOS = '1'
                                       AND P.CDPRODUTO     = IP.CDPRODUTO
                                       AND TMP.CDREGISTRO  = 'C380'
                                       AND TMP.CDCAMPO4    = IT.CDFILIAL
                                       AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                       AND TMP.CDCAMPO4    = IP.CDFILIAL
                                       AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                       AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                       AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                       AND P.CDPRODUTO     = R.CDPRODUTO(+)
                                       AND P_LIVROMAG      = R.CDLIVROMAG(+))
                                     GROUP BY CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE,
                                           CDNATUREC, VRALIQITEM, CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT), IDUTCDEXTPRONF, CDARVORIG)LOOP
               V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'))||'02'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),REGC381.C381);

               V_SEQC   := NVL(V_SEQC,0)+1;
               V_PRODUTO:=NULL;

               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC381.CDARVPROD
                  AND CDREGISTRO = '0200'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));

               IF (V_PRODUTO IS NULL) AND (REGC381.CDARVPROD IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB,CDCAMPO5,CDCAMPO6)
                  VALUES
                     ('0200', V_SEQESTAB, REGC381.CDARVPROD,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')),REGC381.CDARVORIG, REGC381.IDUTCDEXTPRONF);
               END IF;

               V_UNID:= NULL;
               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC381.SGUNIDADE
                  AND CDREGISTRO = '0190'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));
               IF (V_UNID IS NULL) AND (REGC381.SGUNIDADE IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                  VALUES
                     ('0190', V_SEQESTAB, REGC381.SGUNIDADE,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')));
               END IF;

               /* CODIGO DA CONTA CONTABIL */
               BEGIN
                  SELECT MAX(CDCHAVEREG)
                    INTO V_COD_CC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDCHAVEREG = REGC381.COD_CTA
                     AND CDREGISTRO = '0500';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_COD_CC := NULL;
               END;

               IF (V_COD_CC IS NULL) AND (REGC381.COD_CTA IS NOT NULL) THEN
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                  VALUES
                     ('0500', V_SEQCCTBL, REGC381.COD_CTA, NULL);
               END IF;
            END LOOP;

            FOR REGC385 IN (SELECT '|C385'                                                              ||'|'||
                                   CDSITUTRIBITNFE                                                      ||'|'||
                                   CDARVPROD                                                            ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRTOTAITEM),'9999999999900.00')),'.',',')  ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRBASECALCIT),'9999999999900.00')),'.',',')||'|'||
                                   REPLACE(LTRIM(TO_CHAR(VRALIQITEM,'9900.0000')),'.',',')              ||'|'||
                                   ''                                                                   ||'|'||
                                   ''                                                                   ||'|'||
                                   REPLACE(LTRIM(TO_CHAR(SUM(VRIMPOSTOIT),'9999999999900.00')),'.',',') ||'|'||
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT)                   ||'|'/*CODIGO DA CONTA ANALITICA*/ AS C385,
                                   CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE, CDNATUREC, SUM(VRTOTAITEM) AS VRTOTAITEM,
                                   SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,VRALIQITEM, MAX(CDFILIEMIT) AS CDFILIEMIT,
                                   CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT)AS COD_CTA, IDUTCDEXTPRONF, CDARVORIG
                              FROM (SELECT ROUND(IP.VRTOTAITEM,2) AS VRTOTAITEM,
                                           IT.CDTPCREDPICOITE,
                                           DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_COFINS,'B','1'),0) AS VRBASECALCIT,
                                           ROUND(IT.VRALIQITEM,4) AS VRALIQITEM,
                                           ROUND(DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_COFINS,'I','1'),0),2) AS VRIMPOSTOIT,
                                           IT.CDNATUBCALPCIT,
                                           IT.CDSITUTRIBITNFE,
                                           DECODE(TMP.CDCAMPO10,'S',NVL(P.CDPRODINTE,P.CDARVPROD),P.CDARVPROD) AS CDARVPROD,
                                           P.SGUNIDADE,
                                           IT.CDFISCALIT,
                                           NVL(IT.CDNATUREC,R.CDNATUREC) AS CDNATUREC,
                                           TMP.CDCAMPO7 AS CDFILIEMIT,
                                           P.CDPRODUTO,
                                           TMP.CDCAMPO9 AS CDTIPOOPER,
                                           TMP.CDCAMPO10 AS IDUTCDEXTPRONF, P.CDARVPROD AS CDARVORIG
                                      FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, PRODUTO P, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R
                                     WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                       AND IM.CDIMPOSTONFE  = P_COFINS
                                       AND IT.NRLANCTONF   = IP.NRLANCTONF
                                       AND IT.CDFILIAL     = IP.CDFILIAL
                                       AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                       AND IT.NRITPROIMPOS = '1'
                                       AND P.CDPRODUTO     = IP.CDPRODUTO
                                       AND TMP.CDREGISTRO  = 'C380'
                                       AND TMP.CDCAMPO4    = IT.CDFILIAL
                                       AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                       AND TMP.CDCAMPO4    = IP.CDFILIAL
                                       AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                       AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                       AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                       AND P.CDPRODUTO     = R.CDPRODUTO(+)
                                       AND P_LIVROMAG      = R.CDLIVROMAG(+))
                                     GROUP BY CDNATUBCALPCIT, CDTPCREDPICOITE, CDSITUTRIBITNFE, CDARVPROD, SGUNIDADE,CDNATUREC,
                                           VRALIQITEM, CONTCTBL_SPED('S',CDPRODUTO,CDTIPOOPER,CDFILIEMIT), IDUTCDEXTPRONF, CDARVORIG)LOOP

               V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
               INSERT INTO ARQMAGPISCOFINS
                  (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
               VALUES
                  (P_NRSEQARQMAG,'303'||LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'))||'02'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),REGC385.C385);
               V_SEQC   := NVL(V_SEQC,0)+1;
               V_PRODUTO:=NULL;

               /* CODIGO DO PRODUTO */
               SELECT MAX(CDCHAVEREG)
                 INTO V_PRODUTO
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC385.CDARVPROD
                  AND CDREGISTRO = '0200'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));

               IF (V_PRODUTO IS NULL) AND (REGC385.CDARVPROD IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB,CDCAMPO5,CDCAMPO6)
                  VALUES
                     ('0200', V_SEQESTAB, REGC385.CDARVPROD,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')), REGC385.CDARVORIG, REGC385.IDUTCDEXTPRONF);
               END IF;

               V_UNID:= NULL;
               /* UNIDADE DE MEDIDA */
               SELECT MAX(CDCHAVEREG)
                 INTO V_UNID
                 FROM TMP_REGDADOSSPED_PIS
                WHERE CDCHAVEREG = REGC385.SGUNIDADE
                  AND CDREGISTRO = '0190'
                  AND CDESTAB = LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000'));

               IF (V_UNID IS NULL) AND (REGC385.SGUNIDADE IS NOT NULL) THEN
                  V_SEQESTAB := NVL(V_SEQESTAB,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
                  VALUES
                     ('0190', V_SEQESTAB, REGC385.SGUNIDADE,NULL,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')));
               END IF;

               /* CODIGO DA CONTA CONTABIL */
               BEGIN
                  SELECT MAX(CDCHAVEREG)
                    INTO V_COD_CC
                    FROM TMP_REGDADOSSPED_PIS
                   WHERE CDCHAVEREG = REGC385.COD_CTA
                     AND CDREGISTRO = '0500';
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_COD_CC := NULL;
               END;

               IF (V_COD_CC IS NULL) AND (REGC385.COD_CTA IS NOT NULL) THEN
                  V_SEQCCTBL := NVL(V_SEQCCTBL,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED_PIS
                     (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                  VALUES
                     ('0500', V_SEQCCTBL, REGC385.COD_CTA, NULL);
               END IF;
            END LOOP;
            /*INSERE O VALOR REFERENTE AO PIS PARA SAIDAS(DEBITO)*/
            /*SEPARA OS VALORES DO C381 POR REGIME, PARA GERAR O M200 CORRETAMENTE*/
            FOR REGC381_VR IN (SELECT IT.CDTPCREDPICOITE,
                                      SUM(DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_PIS,'B','1'),0)) AS VRBASECALCIT,
                                      ROUND(IT.VRALIQITEM,4) AS VRALIQITEM,
                                      SUM(ROUND(DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_PIS,'I','1'),0),2)) AS VRIMPOSTOIT,
                                      IT.CDSITUTRIBITNFE,
                                      MAX(TMP.CDCAMPO7) AS CDFILIEMIT,
                                      IT.CDNATUBCALPCIT,
                                      SUM(ROUND(IP.VRTOTAITEM,2)) AS VRTOTAITEM,
                                      NVL(IT.CDNATUREC,R.CDNATUREC) AS CDNATUREC,
                                      F.IDCUMUPISCOFIL,
                                      CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7) AS COD_CTA
                                 FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R, FILIAL F
                                WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_PIS
                                  AND IT.NRLANCTONF   = IP.NRLANCTONF
                                  AND IT.CDFILIAL     = IP.CDFILIAL
                                  AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                  AND IT.NRITPROIMPOS = '1'
                                  AND TMP.CDREGISTRO  = 'C380'
                                  AND TMP.CDCAMPO4    = IT.CDFILIAL
                                  AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                  AND TMP.CDCAMPO4    = IP.CDFILIAL
                                  AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                  AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                  AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                  AND IP.CDPRODUTO    = R.CDPRODUTO(+)
                                  AND P_LIVROMAG      = R.CDLIVROMAG(+)
                                  AND TMP.CDCAMPO7    = F.CDFILIAL
                                GROUP BY IT.CDTPCREDPICOITE, ROUND(IT.VRALIQITEM,4), IT.CDSITUTRIBITNFE, IT.CDNATUBCALPCIT,
                                      NVL(IT.CDNATUREC,R.CDNATUREC), F.IDCUMUPISCOFIL, CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7)) LOOP
            V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
            INSERT INTO TMP_REGBLOCOM_PIS
               (CHAVENOTA, CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF,CDNATUREC,CDESTAB,NRINSJUREST,CDCONTCTBL)
            VALUES
               ('C381'||REGC381_VR.CDFILIEMIT,'M200',V_TMPBLCM,REGC381_VR.CDTPCREDPICOITE,REGC381_VR.VRBASECALCIT,REGC381_VR.VRALIQITEM,'P',REGC381_VR.VRIMPOSTOIT,REGC381_VR.CDSITUTRIBITNFE, REGC381_VR.CDFILIEMIT,REGC381_VR.CDNATUBCALPCIT,'0',REGC381_VR.VRTOTAITEM,REGC381_VR.CDNATUREC,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')),C_REGC380.NRINSJUREST,REGC381_VR.COD_CTA);

            END LOOP;
            /*INSERE O VALOR REFERENTE AO COFINS SAIDAS(DEBITO)*/
            /*SEPARA OS VALORES DO C385 POR REGIME, PARA GERAR O M600 CORRETAMENTE*/
            FOR REGC385_VR IN (SELECT IT.CDTPCREDPICOITE,
                                      SUM(DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_COFINS,'B','1'),0)) AS VRBASECALCIT,
                                      ROUND(IT.VRALIQITEM,4) AS VRALIQITEM,
                                      SUM(ROUND(DECODE(IT.CDFISCALIT,'1',VALOR_IMPOSTO_ITEM_REDUZ(IT.CDFILIAL,IT.NRLANCTONF,IT.NRSEQITPROD,P_COFINS,'I','1'),0),2)) AS VRIMPOSTOIT,
                                      IT.CDSITUTRIBITNFE,
                                      MAX(TMP.CDCAMPO7) AS CDFILIEMIT,
                                      IT.CDNATUBCALPCIT,
                                      SUM(ROUND(IP.VRTOTAITEM,2)) AS VRTOTAITEM,
                                      NVL(IT.CDNATUREC,R.CDNATUREC) AS CDNATUREC,
                                      F.IDCUMUPISCOFIL,
                                      CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7) AS COD_CTA
                                 FROM ITEMPROIMPOS IT, ITEMPRODUTO IP, TMP_REGDADOSSPED_PIS TMP, IMPOSTO IM, RELACPRODITGEN R, FILIAL F
                                WHERE IT.CDIMPOSTO    = IM.CDIMPOSTO
                                  AND IM.CDIMPOSTONFE = P_COFINS
                                  AND IT.NRLANCTONF   = IP.NRLANCTONF
                                  AND IT.CDFILIAL     = IP.CDFILIAL
                                  AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                  AND IT.NRITPROIMPOS = '1'
                                  AND TMP.CDREGISTRO  = 'C380'
                                  AND TMP.CDCAMPO4    = IT.CDFILIAL
                                  AND TMP.CDCAMPO5    = IT.NRLANCTONF
                                  AND TMP.CDCAMPO4    = IP.CDFILIAL
                                  AND TMP.CDCAMPO5    = IP.NRLANCTONF
                                  AND TMP.CDESTAB     = C_REGC380.ESTABELECIMENTO
                                  AND TMP.CDCAMPO1    = C_REGC380.DTEMISSAO
                                  AND IP.CDPRODUTO    = R.CDPRODUTO(+)
                                  AND P_LIVROMAG      = R.CDLIVROMAG(+)
                                  AND CDCAMPO7        = F.CDFILIAL
                                GROUP BY IT.CDTPCREDPICOITE, ROUND(IT.VRALIQITEM,4), IT.CDSITUTRIBITNFE, IT.CDNATUBCALPCIT,
                                      NVL(IT.CDNATUREC,R.CDNATUREC), F.IDCUMUPISCOFIL, CONTCTBL_SPED('S',IP.CDPRODUTO,TMP.CDCAMPO9,TMP.CDCAMPO7)) LOOP

               V_TMPBLCM:= NVL(V_TMPBLCM,0)+1;
               INSERT INTO TMP_REGBLOCOM_PIS
                  (CHAVENOTA,CDREGISTRO,CDCONTREGI,CDTPCRED,VRBCCRED,VRALIQCRED,IDTPALIQ,VRCRED,CSTPISCOFINS,CDFILIAL,CDNATUBCALPCIT,VRIMPRETIDO,VRTOTNF, CDNATUREC,CDESTAB,NRINSJUREST,CDCONTCTBL)
               VALUES
                  ('C385'||REGC385_VR.CDFILIEMIT,'M600',V_TMPBLCM,REGC385_VR.CDTPCREDPICOITE,REGC385_VR.VRBASECALCIT,REGC385_VR.VRALIQITEM,'P',REGC385_VR.VRIMPOSTOIT,REGC385_VR.CDSITUTRIBITNFE,REGC385_VR.CDFILIEMIT,REGC385_VR.CDNATUBCALPCIT,'0',REGC385_VR.VRTOTAITEM,REGC385_VR.CDNATUREC,LTRIM(TO_CHAR(C_REGC380.ESTABELECIMENTO,'000')),C_REGC380.NRINSJUREST,REGC385_VR.COD_CTA);
            END LOOP;
         END LOOP;

     -----------------------------------------------------------------/*GERACAO DAS ROTINAS DE ECF*/-----------------------------------------------------------------------
         /*Em SPED_PIS_COFINS_BLOCOC_ECF sao gerados registro 0140 alterando o V_CONTEST no out da funcao*/
         V_TOTBLCC := SPED_PIS_COFINS_BLOCOC_ECF(V_CONTEST,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_CDEMPRESA,P_PIS,P_COFINS,P_LIVROMAG,NVL(V_SEQC,0),P_IDCONSPRODEXT,V_COUNTBL0ECF,V_CONTEST);
         V_SEQC    := NVL(V_TOTBLCC,0);
         V_TOTBLC0 := NVL(V_TOTBLC0,0) + NVL(V_COUNTBL0ECF,0);
      END IF;/*FIM ESCRITURACAO DETALHADA*/
   --------------------------------------------------------------------------------   /*CHAMADA DO BLOCO F */------------------------------------------------------------
      /* CHAMADA SPED_PIS_COFINS_BLOCOF - Pode gerar internamente registro 0140 */
      V_TOTALBCLF:= SPED_PIS_COFINS_BLOCOF(P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_CDINCTRIB,P_CRTESCRITUR,P_PIS,P_PIS_RET_E,P_PIS_RET_S,P_COFINS,P_COFINS_RET_E,P_COFINS_RET_S,V_CONTEST,P_LIVROMAG,V_SEQESTABBLCF);
      V_SEQESTAB:= NVL(V_SEQESTAB,0) +  NVL(V_SEQESTABBLCF,0);
      V_TOTBLC0:= NVL(V_TOTBLC0,0) + NVL(V_SEQESTABBLCF,0);
   -------------------------------------------/*GERA O 0140 PARA ARQUIVOS SEM MOVIMENTO*/---------------------------------------------------------------------------------
      IF ((V_SEMMOVIMENTO = 'S') AND (NVL(V_TOTBLCC,0) <= 0) AND (NVL(V_TOTALBCLF,0) <= 0))  THEN /*VERIFICA SE O ARQUIVO NAO TEVE NENHUMA NOTA FISCAL PARA GERAR O 0140*/
         V_TOTBLC0  := NVL(V_TOTBLC0,0)+1;
         V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+1;
         V_CONTEST  := NVL(V_CONTEST,0)+1;
         V_NEWESTAB := V_CONTEST;
         SELECT '|0140'         ||'|'||
                LTRIM(TO_CHAR(V_NEWESTAB,'000'))      ||'|'||
                E.NMRAZSOCEMPR  ||'|'||
                LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(E.NRINSJUREMPR,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') ||'|'||
                E.SGESTADO     ||'|'||
                ''/*REPLACE(REPLACE(REPLACE(REPLACE(IE.CDINSCESTA,'.',''),'/',''),'-',''),'\','')*/ ||'|'||
                M.CDMUNICIBGE   ||'|'||
                ''             ||'|'||
                ''             ||'|' AS REG,
                LPAD(TRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(E.NRINSJUREMPR,'.',''),'/',''),'-',''),'\',''),' ',''),CHR(10),''),CHR(9),'')),14,'0') AS INSJUREST
           INTO V_REG_0140, V_INSJUREST
           FROM EMPRESA E, MUNICIPIO M
          WHERE E.CDEMPRESA    = P_CDEMPRESA
            AND E.CDPAIS       = M.CDPAIS
            AND E.SGESTADO     = M.SGESTADO
            AND E.CDMUNICIPIO  = M.CDMUNICIPIO;

         INSERT INTO ARQMAGPISCOFINS
            (NRSEQARQMAG,NRORDREGARQMAG,DSREGARQMAG)
         VALUES
            (P_NRSEQARQMAG,'104'||LTRIM(TO_CHAR(V_CONTEST,'000')),V_REG_0140);

         V_SEQESTAB:= NVL(V_SEQESTAB,0)+1;
         INSERT INTO TMP_REGDADOSSPED_PIS
           (CDREGISTRO, CDCONTREGI, CDCHAVEREG,CDCAMPO1,CDESTAB)
         VALUES
           ('0140', V_SEQESTAB, V_INSJUREST ,NULL,LTRIM(TO_CHAR(V_CONTEST,'000')));
      END IF;

   ------------------------------------------/*REGISTRO 0111 - RATEIO PROPORCIONAL*/-------------------------------------------------------------------------------------
      /*REGISTRO 0111*/
      IF P_INDAPROCRED = '2' THEN
         FOR REG_0111 IN (SELECT '|0111'                                                                ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRRECNCINT),   '9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRRECNCUMISEN),'9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(RECNCUMEXP),   '9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(VRRECCUM),     '9999999999900.00')),'.',',') ||'|'||
                                 REPLACE(LTRIM(TO_CHAR(SUM(NVL(VRRECNCINT,0)+NVL(VRRECNCUMISEN,0)+NVL(RECNCUMEXP,0)+NVL(VRRECCUM,0)),'9999999999900.00')),'.',',') ||'|' AS REG0111
                            FROM (SELECT  CASE WHEN CSTPISCOFINS NOT IN ('06','07', '08','09') THEN DECODE(IDCUMUPISCOFIL,'S',SUM(VRCRED),0) ELSE 0 END  AS VRRECNCINT,
                                          CASE WHEN CSTPISCOFINS IN ('06','07', '08','09') THEN SUM(VRCRED) ELSE 0 END AS VRRECNCUMISEN,
                                          '0' AS RECNCUMEXP,
                                          DECODE(IDCUMUPISCOFIL,'N',SUM(VRCRED),0) AS VRRECCUM
                                     FROM TMP_REGBLOCOM_PIS T, FILIAL F
                                    WHERE CDREGISTRO = 'M200'
                                      AND T.CDFILIAL = F.CDFILIAL
                                    GROUP BY IDCUMUPISCOFIL, CSTPISCOFINS)
                           GROUP BY '|0111')LOOP

            V_TOTLINHAS := NVL(V_TOTLINHAS,0)+1;
            V_TOTBLC0   := NVL(V_TOTBLC0,0)+1;
            INSERT INTO ARQMAGPISCOFINS
               (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
            VALUES
               (P_NRSEQARQMAG,'103'||LPAD(RTRIM(V_TOTLINHAS),22,'0'),REG_0111.REG0111);
         END LOOP;
      END IF;
--------------------------/*CHAMADA DO BLOCO M - APURACAO DO PIS E COFINS*/-----------------------------------------------
      /*GERA BLOCO M*/
      V_TOTBLCM := SPED_PIS_COFINS_BLOCOM(V_CONTEST,P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_LIVROMAG,P_CDINCTRIB,P_GERABCLP,P_PIS,P_COFINS, V_GERADEVOLVEND,P_VERSAO,V_CONTBLC0M);
      V_TOTBLC0 := NVL(V_TOTBLC0,0) + NVL(V_CONTBLC0M,0);
   END IF;
-------------------------------------------------/*CHAMADA DO BLOCO P*/---------------------------------------------------
   IF P_GERABCLP IN ('1','2') THEN
      V_RESULTADO:= SPED_PIS_COFINS_BLOCOP(P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,V_SEQESTAB,V_CONTEST,V_COUNTBL0P);
      V_TOTBLCP  := SUBSTR(V_RESULTADO,1,20);
      V_TOTBLC0  := NVL(V_TOTBLC0,0) + NVL(V_COUNTBL0P,0);
   END IF;
-------------------------------------------------/*CHAMADA DO BLOCO 1*/---------------------------------------------------
   /*GERA BLOCO 1*/
   /*Pode gerar internamente registro 0140*/
   V_TOTBLC1 := SPED_PIS_COFINS_BLOCO1(P_CDEMPRESA,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_PIS,P_COFINS,P_GERABCLP,P_CRTESCRITUR,P_VERSAO,NVL(V_SEQ1,0),V_CONTEST,V_CONTEST,V_COUNTBL01);
   V_TOTBLC0 := NVL(V_TOTBLC0,0) + NVL(V_COUNTBL01,0);
------------------------------------------------/*INSERE ABERTURA E FECHAMENTO DOS BLOCOS*/ ------------------------------
   /*O A ABERTURA DO BLOCO A */
   IF V_TOTBLCA > 0 THEN
      V_REG_A001 := '|A001|0|';
   ELSE
      V_REG_A001 := '|A001|1|';
   END IF;

   /*INSERE O REGISTRO A001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'201',V_REG_A001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   V_TOTBLCA:= NVL(V_TOTBLCA,0)+2;

   V_SEQA:= NVL(V_SEQA,0)+2;
   /*INSERE O BLOCO A990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'208','|A990|'||NVL(V_SEQA,2)||'|');

   /*O A ABERTURA DO BOCO C */
   IF V_TOTBLCC > 0 THEN
      V_REG_C001 := '|C001|0|';
   ELSE
      V_REG_C001 := '|C001|1|';
   END IF;

   /*INSERE O REGISTRO C001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'301',V_REG_C001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/

   V_SEQC:= NVL(V_SEQC,0)+2;
   /*INSERE O BLOCO C990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'318','|C990|'||NVL(V_SEQC,2)||'|');

   /*O A ABERTURA DO BOCO D */
   IF V_TOTBLCD > 0 THEN
      V_REG_D001 := '|D001|0|';
   ELSE
      V_REG_D001 := '|D001|1|';
   END IF;

   /*INSERE O REGISTRO D001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'401',V_REG_D001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/

   V_SEQD:= NVL(V_SEQD,0)+2;
   /*INSERE O BLOCO D990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'416','|D990|'||NVL(V_SEQD,2)||'|');

   /*ABERTURA DO BLOCO F*/
   IF V_TOTALBCLF > 0 THEN
      V_REG_F001 := '|F001|0|';
   ELSE
      V_REG_F001 := '|F001|1|';
   END IF;

   /*INSERE O REGISTRO F001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'501',V_REG_F001);
   V_TOTLINHAS := NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/

   V_TOTALBCLF := NVL(V_TOTALBCLF,0) + 2;
   /*INSERE O BLOCO F990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'509','|F990|'||NVL(V_TOTALBCLF,2)||'|');

   IF V_TOTBLCM > 0 THEN
      V_REG_M001 := '|M001|0|';
   ELSE
      V_REG_M001 := '|M001|1|';
   END IF;

   /*INSERE O REGISTRO M001*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'601',V_REG_M001);
   V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/

   V_TOTBLCM:= NVL(V_TOTBLCM,0)+2;/*INSERE 2 DEVIDO AO ENCERRAMENTO*/
   /*INSERE O BLOCO M990 - ENCERRAMENTO*/
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'690','|M990|'||V_TOTBLCM||'|');

   IF P_GERABCLP IN ('1','2') THEN
      IF V_TOTBLCP > 0 THEN
         V_REG_P001 := '|P001|0|';
      ELSE
         V_REG_P001 := '|P001|1|';
      END IF;
   END IF;

   IF P_GERABCLP IN ('1','2') THEN
      /*INSERE O REGISTRO P001*/
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'701',V_REG_P001);
      V_TOTLINHAS:= NVL(V_TOTLINHAS,0)+2; /*INSERE 2 DEVIDO AO ENCERRAMENTO*/

      V_TOTBLCP:= NVL(V_TOTBLCP,0) + 2;
      /*INSERE O BLOCO P990 - ENCERRAMENTO*/
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'709','|P990|'||V_TOTBLCP||'|');
   END IF;

   /*INSERE O REGISTRO 1001*/
   IF V_TOTBLC1 > 0 THEN
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'801','|1001|0|');
   ELSE
      INSERT INTO ARQMAGPISCOFINS
         (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
      VALUES
         (P_NRSEQARQMAG,'801','|1001|1|');
   END IF;
   V_TOTBLC1:= NVL(V_TOTBLC1,0)+1;

   /*INSERE O BLOCO 1990 - ENCERRAMENTO*/
   V_TOTBLC1 := NVL(V_TOTBLC1,0)+1;
   INSERT INTO ARQMAGPISCOFINS
      (NRSEQARQMAG ,NRORDREGARQMAG,DSREGARQMAG)
   VALUES
      (P_NRSEQARQMAG,'803'||V_TOTBLC1,'|1990|'||V_TOTBLC1||'|');

   V_TOTLINHAS:= NVL(SPED_PIS_COFINS_BLOCO9(NVL(V_TOTBLCA,0),NVL(V_TOTBLCC,0),NVL(V_TOTBLCD,0),NVL(V_TOTBLC0,0),P_GERABCLP,P_LIVROMAG,P_NRSEQARQMAG,P_DTINICIAL,P_DTFINAL,P_IDFORAPER),0);
   RETURN(V_TOTLINHAS);
END;
/