function bgmodel(filename,MAXFRAMES)

rows=288;
cols=384;
bgimage=uint8(zeros(96,cols,3));
bghist=uint8(zeros(72,cols,3,1600));

for h = 0 : 72 : 216

    for i = 0 : MAXFRAMES-1
      if i < 10
        currentimagergb = imread(['../',filename,'/JPEGS/',filename,'000',int2str(i),'.jpg'],'jpg');
      elseif i < 100
        currentimagergb = imread(['../',filename,'/JPEGS/',filename,'00',int2str(i),'.jpg'],'jpg');
      elseif i < 1000
        currentimagergb = imread(['../',filename,'/JPEGS/',filename,'0',int2str(i),'.jpg'],'jpg');
      else
        currentimagergb = imread(['../',filename,'/JPEGS/',filename,int2str(i),'.jpg'],'jpg');
      end
      bghist(1:72,:,:,i+1)=currentimagergb(h+1:h+72,:,:);
    end
    
    % initialize background
    data = zeros(MAXFRAMES,1);
    for r = 1 : 72
    [filename,' ',int2str(r)]
      for c = 1 : cols
        for d = 1 : 3
          for k = 1 : MAXFRAMES
            data(k) = double(bghist(r,c,d,k));
          end
          bgimage(h+r,c,d)=uint8(median(data));
        end
      end
    end

end
%      figure(2)
%      image(bgimage)
imwrite(bgimage,['bg_',filename,'.ppm'],'ppm')
