function foto = smoothgrab(frames)
persistent VideoInitialized vid;
% Grab n frames and produce noise-free single frame
% Function computes arithmetic mean of every pixel
% so random noise is reduced.
% SYNTAX        shot = smoothgrab(n)
% shot is [x,y,RGB] picture made from n video frames

if VideoInitialized == 1
    disp('Video device already initialized')
    vid = videoinput('winvideo',1);                 % Can it be done
    set(vid.source,'AnalogVideoFormat','pal_i');    % by separate function
    set(vid,'FramesPerTrigger',frames);             % if multi.dev. used?
else
            vid = videoinput('winvideo',1);
            disp('First video initialization: 5 seconds warm-up')
            start(vid);
            pause(5); % perform warm-up
            stop(vid);
            delete(vid);
            clear vid;
    vid = videoinput('winvideo',1);
    set(vid.source,'AnalogVideoFormat','pal_i');
    set(vid,'FramesPerTrigger',frames);
    VideoInitialized = 1;
end

start(vid);
wait(vid,10);
foto = getdata(vid);
%   delete(vid);    % will be done when function terminates
%   clear vid;
res = size(foto);
foto = uint16(foto); % Arithm.main: uint8 overflow prevention in 'for' loop 
for n=frames:-1:2
    foto(:,:,:,1)=foto(:,:,:,1)+foto(:,:,:,n);
    foto(:,:,:,n)=[];
end

foto(:,:,:)=foto(:,:,:)/frames; % DON'T DO THAT when data analysis
foto = uint8(foto); % Back to image (for viewing only)
