function [ sensorImgsOut, noiseImg, imgTransFactor ] = convertIrrToSensorImgs( sensorIrr,maskCube, AGWNoiseMag, usePoissNoise)
% This function will take an array of irradiance images incident on a
% filter array, transfer the irradiance throught the appropriate filters
% and add sensor noise as specified. Note that this function does not
% approximate non-linear sensor characteristics like saturation.
%   
%   sensorIrr - an array of sensor inputs. Must be of size MxNxFxT where
%   MxN is the array size in pixels, F is the number filters, and T is
%   analogous to time (can jsust be a set of images to model some sample
%   distribution). Note that input should be be the number of photo
%   electrons incident on a filter free sensor.
%
%   maskCube - an array of sensor masks. This can be obtained from the
%   FiltArrayDesigner GUI.
%
%   AGWNoiseMag - the noise magnitude. Referenced to the mean irradiance on
%   the sensor (after passing through the filter array) itself. This means
%   that the mean of the noise will be equal to AGWNoiseMag*100 percent of
%   the sensor image mean.
%
%   usePoissNoise - if true use a Poisson Noise model at the image plane.

[numIrrY,numIrrX,numIrrF,numIrrT] = size(sensorIrr);
[numCubeY,numCubeX,numCubeF] = size(maskCube);

if (numIrrY ~= numCubeY) || (numIrrX ~= numCubeX) || (numIrrF ~= numCubeF)
    error('X,Y,F dimensions of maskCube and sensorIrr must match!');
    return;
end
imgTot = zeros(numIrrY,numIrrX,numIrrT);
for k = 1:numIrrF
%     baseImgMean = mean(mean(sensorIrr(:,:,k,:),1),2);
%     baseImgMax = max(max(sensorIrr(:,:,k,:)));
%     baseImgMin = min(min(sensorIrr(:,:,k,:)));
%     baseMax(k,:) = baseImgMax;
%     baseMin(k,:) = baseImgMin;
%     baseMean(k,:) = baseImgMean;
    
    imgTot = imgTot + bsxfun(@times,squeeze(sensorIrr(:,:,k,:)),squeeze(maskCube(:,:,k)));
    imgTransFactor(k) = mean(mean(maskCube(:,:,k))); %this should always be < 1 for passive filters.     
end

if usePoissNoise
    sensorImgsOut = fPoissrnd( imgTot, 1000 );       
end

if AGWNoiseMag > 0
      meanImgs = squeeze(mean(mean(imgTot,1),2));
%       randNoise = bsxfun(@times,AGWNoiseMag.*randn(numIrrY,numIrrX,numIrrT),meanImgs);
      randNoise = AGWNoiseMag.*randn(numIrrY,numIrrX,numIrrT);
      randNoise = bsxfun(@times,permute(randNoise,[3,1,2]),meanImgs);
      sensorImgsOut = round(sensorImgsOut + permute(randNoise,[2,3,1]));
      %we know that at a low number of p-electrons this causes de-whitening
      %of the noise.
      sensorImgsOut(sensorImgsOut < 0) = 0;
end
noiseImg = imgTot - sensorImgsOut;
end

