% correlations found from linear_spill
function janitor(paths, S, files, nuh)
    %S = [1.0000    0.3201    0.2223; 0.1568    1.0000    0.3792; 0.1095    0.7977    1.0000];
    %path = "/Volumes/home/test/calib/standard_somespill/z001_t001.cam4.tif";
    path = strjoin(["/Volumes/home/test/calib/" paths], "");
    if nuh
        path=paths;
    end
    mkdir(strjoin([path "/clean"], ""))
    
    fprintf(path);
    fprintf("\n");
    mask = "bggr"; 
    for file_index = 1:size(files,2)
        
        name = files(file_index)
        mosaic = imread(strjoin([path "/" name], ""));
        spill_img = cast(demosaic(mosaic, mask), 'double')/(bitshift(1, 8) - 1);
        
        % thing is where the unmixed image goes
        thing = zeros(size(spill_img));
        invS = inv(S);
    

        d1 = size(spill_img, 1);
        d2 = size(spill_img, 2);

        % for each pixel in the source image, unmix it. this removes the
        % bayer matrix
        for i = 1:d1
            for j = 1:d2
                thing(i, j, :) = invS * reshape(spill_img(i,j,:), 3, 1);
            end
        end
    
        % get the image channels, and make a new image matrix for the new
        % tiff
        [r, g, b] = imsplit(thing);
        clean_tiff = zeros(size(spill_img, 1:2));
        
        % reapply the bayer matrix
        for i = 1:2:d1
            for j = 1:d2
                clean_tiff(i, j) = b(i, j);
            end
        end
        
        for i = 2:2:d1
            for j = 1:2:d2
                clean_tiff(i, j) = g(i, j);
            end
        end 
        
        for i = 1:2:d1
            for j = 2:2:d2
                clean_tiff(i, j) = g(i, j);
            end
        end 

        for i = 2:2:d1
            for j = 2:2:d2
                clean_tiff(i, j) = r(i, j);
            end
        end 

        % convert back to unsigned 16 bit, as gigatrack expects
        clean_tiff2 = cast(clean_tiff * (bitshift(1, 8) - 1), "uint16");

    
        URI = strjoin([path, "/clean/", name], "");
        
        imwrite(clean_tiff2, URI);
    end
