CREATE OR REPLACE FUNCTION GIAM_TO_SEGMENTO_R(
   P_DTINICIO      IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFIM         IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_CDEMPRESA     IN MAPAAPURAC.CDEMPRESA%TYPE,
   P_CDINSCESTA    IN MAPAAPURAC.CDINSCESTA%TYPE,
   P_NRSEQARQMAG   IN ARQMAGNETICO.NRSEQARQMAG%TYPE,
   P_IDRETIFIC     IN NOTAFISCAL.CDTIPOOPER%TYPE) RETURN NUMBER
AS
   V_CONTREG NUMBER;
BEGIN
   FOR C_REG_R IN (SELECT 'R'                               ||
                          RPAD(CDINSCESTA,11,'0')           ||
                          TO_CHAR(DTFIMPERIODO,'MMYYYY')    ||
                          P_IDRETIFIC                       ||
                          LPAD(NVL(SUBSTR(I.DSITEMMAPR,1,2),'0'),2,'0') ||
                          REPLACE(LTRIM(TO_CHAR(NVL(I.VRITEMMAPR,0),'000000000000.00')),'.')  AS SEG_R
                     FROM MAPAAPURAC M, ITMAPARECUP I
                    WHERE M.CDEMPRESA    = P_CDEMPRESA
                      AND M.CDINSCESTA   = P_CDINSCESTA
                      AND M.DTINIPERIODO = P_DTINICIO
                      AND M.DTFIMPERIODO = P_DTFIM
                      AND M.CDIMPOSTO    = '00'
                      AND M.NRSEQUMAPAPU = I.NRSEQUMAPAPU
                      AND I.IDTIPOITMAPR = 'OD'
                      AND I.VRITEMMAPR   > 0) LOOP

      V_CONTREG := NVL(V_CONTREG,0) + 1;

      INSERT INTO ARQMAGNETICO
         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
         ('10'||LPAD(RTRIM(V_CONTREG), 8, '0'), C_REG_R.SEG_R, P_NRSEQARQMAG);

   END LOOP;
   RETURN(NVL(V_CONTREG,0));
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('GIAM_TO_SEGMENTO_R','0.00.000'); END;
/