clear;
close all;

Config;

[tempList, tempNames] = findSubDir(par.data_dir);
par.file_list = tempList;
par.file_dirs = tempNames;

files = par.file_list{1};
[GT, GTmask] = ReadSat(files{40}, par);
GT = GT ./ 1e+4;
GT = uint8(GT .* 255);

files = par.file_list{1};
[Ref, ~] = ReadSat(files{25}, par);
Ref = Ref ./ 1e+4;
Ref = uint8(Ref .* 255);

num_of_low_clouds = 10;

[H,W,C] = size(GT);

angle0 = 90 - par.sun_elevation;
angle0 = angle0 * pi / 180;

angle1 =  (90 - par.sun_azimuth);
angle1 = angle1 * pi / 180;

for clouds_name_index = 1:num_of_low_clouds
    cloud_height = randi([par.cloud_height_min, par.cloud_height_max], 1) - 10;
    x = tan(angle0)* cloud_height;
    dir = [cos(angle1); sin(angle1)];
    
    v = floor(x*dir);
    
    [sceneID,acquisitionDate,sunElevation,sunAzimuth] = importfile(par.metadata_path);
    min_sun_elevation = min(sunElevation);
    max_sun_elevation = max(sunElevation);
    min_sun_azimuth = min(sunAzimuth);
    max_sun_azimuth = max(sunAzimuth);

    par.sun_elevation = (max_sun_elevation - min_sun_elevation) * rand(1,1) + min_sun_elevation;
    par.sun_azimuth = (max_sun_azimuth - min_sun_azimuth) * rand(1,1) + min_sun_azimuth;

    shade_im = noiseonf([H,W], 1.5);
    shade_im = shade_im - min(min(shade_im));
    min_shade_im = mean(mean(shade_im))*1.2;
    shade_im_mask = shade_im < min_shade_im;
    shade_im = (shade_im - min_shade_im )/ (max(max(shade_im)) - min_shade_im );
    shade_im = shade_im * 255;
    shade_im(shade_im_mask) = 0;
    shade_im = uint8(shade_im);
    shade_im = repmat(shade_im, 1,1,C);
    shade_im = shade_im / 8;

    shadow_shade = zeros(H,W,C);
    if v(2) < 0
        H_row = abs(v(2))+1:H;
        H_base = 1:H-abs(v(2));
    else
        H_row = 1:H-v(2);
        H_base = v(2)+1:H;
    end
    if v(1) < 0
        W_row = abs(v(1))+1:W;
        W_base = 1:W-abs(v(1));
    else
        W_row = 1:W-v(1);
        W_base = v(1)+1:W;
    end
    shadow_shade(H_base ,W_base , :) = shade_im(H_row , W_row, :);
    Nimg = GT + shade_im - uint8(shadow_shade * 0.75);
    
    Nimg2 = Nimg;
    for layer = 1:6
        Nimg2(:, :, layer) = imhistmatch(Nimg(:,:,layer), Ref(:,:,layer));
    end
    Nimg = Nimg2;
    %%
    %Write Thumbnail
    imwrite(Nimg(:,:, [3 2 1]), sprintf('%sThumbnail/lowClouds%i.tif',par.output_folder, clouds_name_index));
    %%
    %Write multi(6)-channel Tiff
    WriteTiff(sprintf('%slowClouds%i.tif',par.output_folder, clouds_name_index), Nimg);
    %%
    %Mask
    mask = GTmask;
    mask(mask == 1) = 0;
    mask(mask == 2) = 0;
    s_mask = shadow_shade(:, :, 1) > 0;
    mask(s_mask) = 1;
    c_mask = shade_im(:, :, 1) > 0;
    mask(c_mask) = 2;
    imwrite(mask, sprintf('%slowClouds%i_mask.tif',par.output_folder, clouds_name_index))
end