function Arrival();

global MatrixIn;
global ValueCount numdev queuecapacity
global NextDepart NextArrive Devices numinput Queue numrefused
global systime

systime=NextArrive;

numinput=numinput+1;

Wrap;

successfulassaut = 0;

if numinput>=ValueCount
    InitAdditionalTransact; 
end;
NextArrive = systime + MatrixIn(2,numinput+1);

if min(Devices) == 0
    
    for i=1:numdev
        if Devices(i) == 0
            point = i;
        end;
    end;
    
    Devices(point) = numinput;
    NextDepart(point) = systime + MatrixIn(3,numinput);
       
else
    successfulassaut = 0;
    for j=1:numdev
        if MatrixIn(4,numinput)>MatrixIn(4,Devices(j))
            
            successfulassaut = 1;
            
            for i=1:length(Queue)
                 if Queue(i) == 0
                 queuepoint = i;
                 break;
                 end;
            end;
    
            MatrixIn(3,Devices(j)) = NextDepart(j) - systime;
            
            for i=1:length(Queue)
                if Queue(i) == 0
                      Queue(i) = Devices(j);
                      Queue(i+1) = 0;
                      break;
                end;
            end;
            
            Sorting;
            
            if queuepoint-1 == queuecapacity
                Queue(queuepoint) = 0;
                numrefused = numrefused + 1;
            end;
            
            Devices(j) = numinput;
            NextDepart(j) = systime + MatrixIn(3,numinput);
            
            break;
            
        end;
    end;
end;

if successfulassaut == 0
    
    for i=1:length(Queue)
        if Queue(i) == 0
            queuepoint = i;
            break;
        end;
    end;
    
    for i=1:length(Queue)
        if Queue(i) == 0
            Queue(i) = numinput;
            Queue(i+1) = 0;
            break;
        end;
    end;
    
    Sorting;
    
    if queuepoint-1 == queuecapacity
        Queue(queuepoint) = 0;
        numrefused = numrefused + 1;
    end;
end;
