%%%%%%%%%%%% clean your workspace
clear
clc

%%%%%%%%%%%% set up variables
a1 = dir('*-*');
a2 = {a1.name};
y = {'NORMALIZED_DISTANCE','pre_ATROPOS_GMM','pre_ATROPOS_GMM_ECCENTRICITY','pre_ATROPOS_GMM_ELONGATION','pre_ATROPOS_GMM_LABEL3_DISTANCE','pre_ATROPOS_GMM_PHYSICAL_VOLUME','pre_ATROPOS_GMM_POSTERIORS1','pre_ATROPOS_GMM_POSTERIORS2','pre_ATROPOS_GMM_POSTERIORS3','pre_ATROPOS_GMM_POSTERIORS4','pre_ATROPOS_GMM_VOLUME_TO_SURFACE_AREA_RATIO','pre_ENTROPY_RADIUS_1','pre_ENTROPY_RADIUS_3','pre_MEAN_RADIUS_1','pre_MEAN_RADIUS_3','pre_NORMALIZED','pre_SIGMA_RADIUS_1','pre_SIGMA_RADIUS_3','pre_SKEWNESS_RADIUS_1','pre_SKEWNESS_RADIUS_3','pre__DIFFERENCE'};


%%%%%%%%%%%% open makefile
fid=fopen('crFIwCSVOV.makefile','w');


%%%%%%%%%%%% set up the path
fprintf(fid,['WORKDIR=/mnt/data/scratch/igilab/data/qayyum/tcga_ov\n']);
fprintf(fid,'\n\n') %leave blank line

%%%%%%%%%%%% print "all" job
fprintf(fid,'all: ');

for jj = 1:length(a2)
    
    fprintf(fid,'job_%s_crFI ', a2{jj}); %all jobs
    
    for jjj = 1:length(y);
        fprintf(fid,'job_%s_wCSV_%s ', a2{jj}, y{jjj});
    end
    
end

fprintf(fid,'job-create-master-sheet');

fprintf(fid,'\n\n'); %leave blank line




for ii = 1:length(a2);
   

% copyheaders/orient/createmask/createFI
fprintf(fid,'job_%s_crFI:\n', a2{ii});
fprintf(fid,'\tcd $(WORKDIR)/%s;c3d %s_grey.nii.gz %s_labels.nii.gz -copy-transform -o %s_labels.nii.gz\n', a2{ii}, a2{ii}, a2{ii}, a2{ii});    %correct headers
fprintf(fid,'\tcd $(WORKDIR)/%s;c3d %s_grey.nii.gz -orient RAI -o %s_grey.nii.gz\n', a2{ii}, a2{ii}, a2{ii});   %reorient grey images to RAI
fprintf(fid,'\tcd $(WORKDIR)/%s;c3d %s_labels.nii.gz -orient RAI -o %s_labels.nii.gz\n', a2{ii}, a2{ii}, a2{ii}); %reorient label maps to RAI
fprintf(fid,'\tcd $(WORKDIR)/%s;../createFeatureImagesOvary.sh -d 3 -x %s_labels.nii.gz -l3 -n pre -a %s_grey.nii.gz -f 0x2 -o ./%s_ -r 1 -r 3 -s 2 -b 4\n', a2{ii}, a2{ii}, a2{ii}, a2{ii}); %create feature images




%%%%%%%%%%%%%%%%%%%%%%%%% Write each FI-value into separate CSV

    for tt = 1:length(y);
%%%% job title
        fprintf(fid,'job_%s_wCSV_%s:\n', a2{ii}, y{tt});

        fprintf(fid,'\tcd $(WORKDIR)/%s;c3d %s_%s.nii.gz %s_mask.nii.gz -lstat > %s_%s.txt\n', a2{ii}, a2{ii}, y{tt}, a2{ii}, a2{ii}, y{tt});
        fprintf(fid,'\tcd $(WORKDIR)/%s;sed -i "1,2d" %s_%s.txt\n', a2{ii}, a2{ii}, y{tt});
        fprintf(fid,'\tcd $(WORKDIR)/%s;sed "s/\\s\\+/,/g" %s_%s.txt > %s_%s.csv\n', a2{ii}, a2{ii}, y{tt}, a2{ii}, y{tt});
        fprintf(fid,'\tcd $(WORKDIR)/%s;sed -i "s/^/%s_%s,/" %s_%s.csv\n', a2{ii}, a2{ii}, y{tt}, a2{ii}, y{tt});

    end
    fprintf(fid,'\n\n'); %leave blank line
end

%%%% create final CSV
fprintf(fid,'job-create-master-sheet:\n');
fprintf(fid,'\tcd $(WORKDIR);touch ./mastersheetOV.csv\n');

for ff = 1:length(a2);;
    for gg = 1:length(y)
    fprintf(fid,'\tcd $(WORKDIR);cat ./%s/%s_%s.csv >> mastersheetOV.csv\n', a2{ff}, a2{ff}, y{gg});
    end
end
fclose(fid); %close makefile