% Try to download the image for the selected gene and slice. It returns the
% name of the file containing the image and an error (0 means ok)

% Information:
% http://community.brain-map.org/confluence/download/attachments/525267/TheABAAPI_Final.pdf?version=2

function [namefile error_log] = downloadABAImage(gene_name, series, slice, OUTPUT_FOLDER)

fid_log = fopen('LogDownload.txt','a');

error_log=0;
downloaded_gene = 0;
namefile = '';

%se la serie non e' specificata, devo trovarla a partire dall'xml del gene
if ~numel(series)

    try
        dataxml = xmlread(strcat('http://www.brain-map.org/aba/api/gene/',gene_name,'.xml'));
    catch e
        disp(e.message)
        error_log = 1;
        fprintf(fid_log, '[ERROR - %s] No xml file for gene %s.\n', datestr(now), gene_name);
        return
    end
    xRoot = dataxml.getDocumentElement;

    allListitems = xRoot.getElementsByTagName('image-series');

    for k = 0:allListitems.getLength-1
        thisListitem = allListitems.item(k);
        seriesList = thisListitem.getElementsByTagName('imageseriesid');
        tmpSeries = seriesList.item(0).getFirstChild.getData;
        planeList = thisListitem.getElementsByTagName('plane');
        plane = planeList.item(0).getFirstChild.getData;
        if numel(tmpSeries) && strcmpi(plane, 'sagittal')
            series = char(tmpSeries);
            break;
        end
    end
end

%se a questo punto non hai ancora trovato la serie e' un problema
if ~numel(series)
    error_log = 1;
    fprintf(fid_log, '[ERROR - %s] No available serie for gene %s.\n', datestr(now), gene_name);
end

referenceAtlasIndexes = zeros(1,2);
[referenceAtlasIndexes(1) referenceAtlasIndexes(2)] = get_ReferenceAtlasIndexes(slice);
if referenceAtlasIndexes(1) == 0 || referenceAtlasIndexes(2) == 0
    error_log=1;
    fprintf(fid_log, '[ERROR - %s] The slice %s does not exist.\n', datestr(now), num2str(slice));
end

if error_log == 0
    %% http://www.brain-map.org/aba/api/imageseries/[imageseriesid].xml
    seriesIDURL = strcat('http://www.brain-map.org/aba/api/imageseries/',series,'.xml');
    try
        str_IDURL = urlread(seriesIDURL);
    catch e
        disp(e.message)
        error_log = 1000;
        if(size(strfind(e.message, 'proxy'),1) > 0)
            fprintf(fid_log, '[ERROR - %s] Error reading xml for series %s (%s) - Connection down.\n', datestr(now), series, gene_name);
        else
            fprintf(fid_log, '[ERROR - %s] Error reading xml for series %s (%s).\n', datestr(now), series, gene_name);
        end
        return
    end 
    imagename_ini_positions = strfind(str_IDURL,'<imageseriesdisplayname>');
    imagename_end_positions = strfind(str_IDURL,'</imageseriesdisplayname>');
    str_name = str_IDURL(imagename_ini_positions+24:imagename_end_positions-1);
    if ~strfind(lower(str_name), lower(gene_name))
        fprintf(fid_log, '[WARNING - %s] The image serie %s does not seem to correspond to the gene %s.\n', datestr(now), series, gene_name);
    end
    images_ini_positions = strfind(str_IDURL,'<position type=''integer''>');
    downloadImagePath_ini_positions = strfind(str_IDURL,'<downloadImagePath>');
    downloadImagePath_end_positions = strfind(str_IDURL,'</downloadImagePath>');
    plane_ini_positions = strfind(str_IDURL,'<plane>');
    plane_end_positions = strfind(str_IDURL,'</plane>');
    iniReferenceAtlasIndex = strfind(str_IDURL,'<referenceatlasindex type=');
    endReferenceAtlasIndex = strfind(str_IDURL,'</referenceatlasindex>');
    if (strfind(str_IDURL(plane_ini_positions+7:plane_end_positions-1),'sagittal')~= 0) % We have tested again that it's Sagittal
        for j=1:size(images_ini_positions,2)
            ReferenceAtlasIndex = str_IDURL(iniReferenceAtlasIndex(1,j)+36:endReferenceAtlasIndex(1,j)-1);

            if (downloaded_gene == 0 && (referenceAtlasIndexes(1) <= str2num(ReferenceAtlasIndex)) && (str2num(ReferenceAtlasIndex) <= referenceAtlasIndexes(2)))
                add_URL = str_IDURL(downloadImagePath_ini_positions(1,j)+19:downloadImagePath_end_positions(1,j)-1);
                webURL = strcat('http://mouse.brain-map.org/aba/api/image?zoom=-1&path=',add_URL);
                converted_gene_name = regexprep(gene_name, '*', 'x');
                converted_gene_name = regexprep(converted_gene_name, '\.', '');
                namefile = strcat(OUTPUT_FOLDER,'\',converted_gene_name,'_',ReferenceAtlasIndex,'_',num2str(slice),'.jpg');
                try
                    urlwrite(webURL,namefile);
                catch e
                    disp(e.message)
                    error_log = 1000;
                    if(size(strfind(e.message, 'proxy'),1) > 0)
                        fprintf(fid_log, '[ERROR - %s] Error reading image for series %s (%s) - Connection down.\n', datestr(now), series, gene_name);
                    else
                        fprintf(fid_log, '[ERROR - %s] Error reading image for series %s (%s).\n', datestr(now), series, gene_name);
                    end
                    return
                end 
                if check_image(namefile) > 0
                    fprintf(1,'%s: download complete.\n',converted_gene_name);
                    downloaded_gene = downloaded_gene + 1;
                    continue;
                end
            end;
        end;
    else
        error_log = 1;
        fprintf(fid_log, '[ERROR - %s] This Gene image serie %s (%s) has not contain Sagittal Slices.\n', datestr(now), series, gene_name);
    end;
    if downloaded_gene == 0
        error_log = 1;
        fprintf(fid_log, '[ERROR - %s] This Gene image serie %s (%s) does not contain Slices for the selected references\n', datestr(now), series, gene_name);
    end
end

if error_log == 0
    fprintf(fid_log, '[OK - %s] Gene image serie %s (%s) downloaded correctly\n', datestr(now), series, gene_name);
end;
fclose(fid_log);

end
