%% COMPUTE_GENE_LIST
% This is the main entry of the program. Set all variables you need to set
% and run. The FILE_GENES must contain in every line NAME_GENE\tGENE_SERIE
% (see example.genes)

addpath('download_images')

this_dir = cd;

% set input
%% SET: put true if you want to start an experiment from scratch, false if you want to continue and old one
BRAND_NEW = true;
%% SET: this is the path where getHippoCampus.m (and others) are
BIN_FOLDER = strcat(this_dir,'/../LocalizationAndFeatureExtraction');
% the existence of this variable
if ~exist('RUNNING_ENTIRE_EXPERIMENT', 'var')
    %% SET: the folder containing all outputs. All experiments must reside here
    OUTPUT_FOLDER = 'C:/Users/Toshiba/Desktop/SanPaolo/Experiments';
    %% SET: the name of the experiment
    EXPERIMENT = 'example';
else
    disp('runExperiment has been called from outside. Some parameters may be overwritten')
end

%% SET: use already downloaded images
USE_ALREADY_DOWNLOADED = true;
%% SET: these are the reference slices that can be used
ALL_SLICES = [36 34 38 32 40 30 42];

%% SET: you can change all these folder/files/selections, but using the standard ones is probably better
% this is the folder containing the experiment. Input/Outputs will be in this place, if not chosen otherwise
EXPERIMENT_FOLDER = strcat(OUTPUT_FOLDER,'/',EXPERIMENT);
% this is the file containing the list of couples gene-serie
if exist('IS_TRAINING', 'var')
    if IS_TRAINING
        FILE_GENES = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'.train');
        EXPERIMENT_FOLDER = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'/train');
    else
        FILE_GENES = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'.test');
        EXPERIMENT_FOLDER = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'/test');
    end
else
    FILE_GENES = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'.test');
end
%this is the folder when the brain images are saved
INPUT_FOLDER = strcat(EXPERIMENT_FOLDER,'/images');
%these are the folders where the tool will look for already downloaded images
DOWNLOADED_FOLDERS = {};
DOWNLOADED_FOLDERS{1} = INPUT_FOLDER;
if exist('IS_TRAINING', 'var')
    if ~IS_TRAINING %is testing
        DOWNLOADED_FOLDERS{2} = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'/train/images');
    end
end
% this is the mat file that contains the variables needed for ranking (generated by GeneticFeatureSelectionToolbox)
if exist('IS_TRAINING', 'var')
    if IS_TRAINING
        RANKING_MAT_FILE = '';
    else
        TRAIN_FOLDER = strcat(OUTPUT_FOLDER,'/',EXPERIMENT,'/train');
        RANKING_MAT_FILE = strcat(TRAIN_FOLDER,'/ranking_variables.mat');
    end
else
    RANKING_MAT_FILE = strcat(EXPERIMENT_FOLDER,'/ranking_variables.mat');
end
% this file will contain the index of the last gene successfully computed (useful for recovering a simulation)
INDEX_GENE = strcat(EXPERIMENT_FOLDER,'/index');
% this is the folder where all the segmented parts are stored
SEGMENTED_FOLDER = strcat(EXPERIMENT_FOLDER,'/segmented');
% this is the folder where all hippocampi are stored
OUT_HIPPO_FOLDER = strcat(EXPERIMENT_FOLDER,'/hippos');
% this is the file where computed features will be stored
OUTPUT_FEATURES_FILE = strcat(EXPERIMENT_FOLDER,'/features.txt');
% this is the file where the results of the ranking (if performed) are stored
OUTPUT_RANKING_FILE = strcat(EXPERIMENT_FOLDER,'/rank.csv');
% this is the name of the log file 
LOG_FILE = strcat(EXPERIMENT_FOLDER,'/log.txt');


addpath(BIN_FOLDER)

hippo_dir = BIN_FOLDER;

%if the folders do not exists, create them
if ~exist(INPUT_FOLDER,'dir'),mkdir(INPUT_FOLDER); end
if ~exist(OUT_HIPPO_FOLDER,'dir'),mkdir(OUT_HIPPO_FOLDER); end
if ~exist(SEGMENTED_FOLDER,'dir'),mkdir(SEGMENTED_FOLDER); end
cd(SEGMENTED_FOLDER)
if ~exist('ca1_border_ext','dir'), mkdir('ca1_border_ext'); end
if ~exist('ca1_border_int','dir'), mkdir('ca1_border_int'); end
if ~exist('ca1_in','dir'), mkdir('ca1_in'); end
if ~exist('ca1_out','dir'), mkdir('ca1_out'); end
if ~exist('ca3_border_ext','dir'), mkdir('ca3_border_ext'); end
if ~exist('ca3_border_int','dir'), mkdir('ca3_border_int'); end
if ~exist('ca3_in','dir'), mkdir('ca3_in'); end
if ~exist('ca3_out','dir'), mkdir('ca3_out'); end
if ~exist('dg_border_ext','dir'), mkdir('dg_border_ext'); end
if ~exist('dg_border_int','dir'), mkdir('dg_border_int'); end
if ~exist('dg_in','dir'), mkdir('dg_in'); end
if ~exist('dg_out_ext','dir'), mkdir('dg_out_ext'); end
if ~exist('dg_out_int','dir'), mkdir('dg_out_int'); end
    
%clean files used in append
if BRAND_NEW
    fid = fopen(INDEX_GENE, 'w');
    fprintf(fid, '%d', 1);
    fclose(fid);
    fid = fopen(OUTPUT_FEATURES_FILE, 'w');
    fclose(fid);
    fid = fopen(OUTPUT_RANKING_FILE, 'w');
    fclose(fid);
end

while 1
    
    logFile = fopen(LOG_FILE,'a');

    cd(this_dir)
    
    %read the gene to do
    fid = fopen(INDEX_GENE, 'r');
    if fid < 0
        fid = fopen(INDEX_GENE, 'w');
        fprintf(fid, '%d', 1);
        fclose(fid)
        fid = fopen(INDEX_GENE, 'r');
    end
    IND = fscanf(fid, '%d');
    fclose(fid);

    %read all genes to do
    fid = fopen(FILE_GENES);
    C = textscan(fid,'%s\t%s');
    
    if IND > length(C{1})
        fclose(fid); 
        fclose('all');
        break
    end
    
    gene_name = char(C{1}(IND));
    converted_gene_name = regexprep(gene_name, '*', 'x');
    converted_gene_name = regexprep(converted_gene_name, '\.', '');
    gene_names{IND} = converted_gene_name;
    serie_names{IND} = char(C{2}(IND));
    fclose(fid); 

    i = IND;
    gene_name = gene_names{i};
    series = serie_names{i};
    success = 0;
    slice_index = 1;
    fprintf(1,'%s: Begin.\n', gene_name);
    while ~success && slice_index < numel(ALL_SLICES) %repeat until you cannot or until you have finished possible slices
        slice = ALL_SLICES(slice_index);
        download_error = 1000;
        if USE_ALREADY_DOWNLOADED
            [file_name download_error] = retrieveABAImage(gene_name, slice, DOWNLOADED_FOLDERS);
        end
        if download_error > 0
            while download_error > 10 %it returns 1000 is there are some problems with the internet (re-do until internet comes up again)
                [file_name download_error] = downloadABAImage(gene_name, series, slice, INPUT_FOLDER);
            end
        end
        if ~download_error
            %clean name of file removing folder and extension
            [pathstr, name] = fileparts(file_name);
            cd(hippo_dir);
            [success sel_slice euclidean pearson features] = getHippoCampus(name,-1, RANKING_MAT_FILE, OUT_HIPPO_FOLDER, INPUT_FOLDER, SEGMENTED_FOLDER, ALL_SLICES(slice_index));
            cd(this_dir);
        end
        slice_index = slice_index + 1;
    end
    if success == 0
        fprintf(1,'%s: Elaboration Failed.\n', gene_name);
        fprintf(logFile, '[ERROR - %s] %s (index: %d) has not been completed successfully in %d tries.\n',datestr(now), gene_name, i, slice_index-1);
    else
        fprintf(1,'%s: Elaboration Complete.\n', gene_name);
        fprintf(logFile, '[OK - %s] %s (index: %d) has been completed succesfully in %d tries.\n',datestr(now), gene_name, i, slice_index-1);
        fid_rank = fopen(OUTPUT_RANKING_FILE,'a');
        fprintf(fid_rank, '%s\t%s\t%f\t%f\n', gene_name, series, euclidean, pearson);
        fclose(fid_rank);
        fid_rank = fopen(OUTPUT_FEATURES_FILE,'a');
        fprintf(fid_rank, '%s\t%s', gene_name, series);
        fprintf(fid_rank, '\t%f', features);
        fprintf(fid_rank, '\n');
        fclose(fid_rank);
    end

    %write next gene to do
    fid = fopen(INDEX_GENE, 'w');
    fprintf(fid, '%d', IND+1);
    fclose(fid);

    fclose(logFile);
    fclose('all');

end

fprintf('EXECUTION COMPLETE!! %d genes have been computed!\n\n', IND-1);
