function Sono_Analysis
%%
%%
global I
global FILE_LOADED 
global h_plot
global hh_brush
global PEAK_INDEX 
global h_line_scan
global dx_pixel;
global p_scale_val_j
global XX_global
global YY_global

XX_global =[];
YY_global =[];
dx_pixel = 1.0;
PEAK_INDEX =  0;
FILE_LOADED = false;
p_scale_val_j  = 0;


f = figure('Visible','off','Position',[1,1,1000,800],'Resize','off', 'Name', 'Sono Analysis', 'NumberTitle','off','Toolbar','none','Color',[1 1 1]);
h_axes = axes('Units','pixels','Position',[30,190,726,601] ,'XTick',[],'YTick',[]);
h_trace_axes = axes('Units','pixels','Position',[30,35,726,145], 'XTick',[],'YTick',[]);

%%PUSHBUTTONS%%
load_sono_file = uicontrol('Style','pushbutton','String','Load',...
                          'Position',[800,400,70,30], 'Callback',{@load_sono_Callback});

h_trace_line = uicontrol('Style','pushbutton','String','Scan',...
                          'Position',[800,350,70,30], 'Callback',{@trace_line_Callback});


h_brush = uicontrol('Style','pushbutton','String','Select',...
                          'Position',[800,300,70,30], 'Callback',{@brush_Callback});

h_fit = uicontrol('Style','pushbutton','String','Fit',...
                          'Position',[900,250,70,30], 'Callback',{@fit_Callback});


h_get = uicontrol('Style','pushbutton','String','Simple',...
                          'Position',[800,250,70,30], 'Callback',{@BrushAction});

h_save_anal= uicontrol('Style','pushbutton','String','Save Analysis',...
                          'Position',[800,50,170,30], 'Callback',{@Save_anal_action});

%%%%h_slide = uicontrol('Style', 'slider',...
%%%%         'Min',-5,'Max',5,'Value',0,...
%%%%        'Position', [800 35 100 30],...
%%%%        'Callback', {@scale_p});   
%%%%
%%%%h_text_scale_p = uicontrol('Style','text','String','0',...
%%%%                           'Position',[910,35,50,30])
%%%%


set(f,'Visible','on');


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%SIGMOID%%
function [y_sig_out] = sig_profile(x,x1,x2,sig1,sig2,amp1,amp2,test_max)
%base function is sigmoid: 
%f(x,x0,sig)=1/(1+exp((-x+x0)/sig))
 y_sig_out = test_max - amp1*mysig(x,x1,sig1)+amp2*mysig(x,x2,sig2);

 function [y] = mysig(x,x0,sig)
   y=ones(1,length(x))./(1+exp((-x+x0)/(sig)));
 end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%FEATURA%%
function  fit_Callback(source,eventdata)
  
  get(h_plot);
  brush_tmp = get(h_plot,'BrushData');
  firstIndex_brush = find(brush_tmp, 1, 'first');
  XX_tmp = get(h_plot,'XData');
  YY_tmp = get(h_plot,'YData');
  XX = XX_tmp(logical(brush_tmp));
  YY = YY_tmp(logical(brush_tmp));


  [trash_me, lft_ref_val] = ginput(1);
  [fall_x1, trash_me] = ginput(1);
  [fall_x2, trash_me] = ginput(1);
  [trash_me, test_min] = ginput(1);
  [raise_x1, trash_me] = ginput(1);
  [raise_x2, trash_me] = ginput(1);
  [trash_me, rgt_ref_val] = ginput(1);

  params0=[(fall_x1+fall_x2)*0.5,...
             (raise_x1+raise_x2)*0.5,...
            fall_x2-fall_x1,...
           raise_x2-raise_x1,...
           lft_ref_val-test_min, ...
           rgt_ref_val-test_min,...           
           0.5*(rgt_ref_val+lft_ref_val)];

  F=@(params,x) sig_profile(x,params(1),params(2),params(3),params(4), params(5),params(6), params(7));
  [params,resnorm,trash_me,exitflag,output] = lsqcurvefit(F,params0,XX,YY);

%  hold on;
%  plot(XX,F(params,XX),'Parent',h_trace_axes);
%  line([params(1) params(1)], [0 0.5*params(7)], 'Color', 'g', 'LineWidth', 2);
%  line([params(2) params(2)], [0 0.5*params(7)], 'Color', 'g', 'LineWidth', 2);
  YY_fit=F(params,XX);

  x_ip = linspace(XX(1),XX(length(XX)),100);
  y_ip = interp1(XX,YY_fit,x_ip,'spline');
 
  y_ip_min = min(y_ip);
  y_ip_max_mean = 0.5*(y_ip(1)+y_ip(length(y_ip)))'
  y_half = y_ip_min + 0.5*(y_ip_max_mean - y_ip_min)

  yHalfMax = y_ip < y_half;

  firstIndex = find(yHalfMax, 1, 'first');
  lastIndex = find(yHalfMax, 1, 'last');


  line(XX, YY_fit,'Color',[.9 .7 .7],'LineWidth', 2);
%  line([params(1) params(2)], [0.5*params(7) 0.5*params(7)], 'Color', [0 0 0], 'LineWidth', 3);
  line([x_ip(firstIndex), x_ip(lastIndex)], [y_half, y_half], 'Color', [0 0 0], 'LineWidth', 3);


  PEAK_INDEX = PEAK_INDEX + 1;
%  fwhm = params(2) - params(1);
  fwhm = -x_ip(firstIndex)+x_ip(lastIndex);

  text(0.5*(x_ip(firstIndex)+x_ip(lastIndex)), y_half + 50 , sprintf('Feature: %d\nDip:%.2f\nFWHM=%.2f mm',PEAK_INDEX, 0.5*(y_ip_max_mean - y_ip_min) ,fwhm),'BackgroundColor',[.9 .7 .7], 'HorizontalAlignment', 'Center');


end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%SAVE%%
function Save_anal_action(source,eventdata)
 %   saveas([h_plot I],'saved','png')  
% h(1)=h_plot
% h(2)= I
% set([load_sono_file h_trace_line  h_brush h_get h_save_anal],'Visible','off')
% saveas(gcf,'saved','png');
% print -dpng -r 

% brush off;
  [file_name, path_name] = uiputfile({'*.jpg;*.tif;*.png;*.gif','All Image Files';...
          '*.*','All Files' },'Save Analysis',...
          'newfile.png')
 [pathstr,name,ext] = fileparts(file_name);
 if strcmp(ext,'')
ext='.png'
 end
 % FileName = 'written';
 set(h_plot,'BrushData',0);
 img = getframe(gcf);
 Imout = imcrop(img.cdata,[0 0 780 800]);
 imwrite(Imout,[strcat(path_name,name),ext]);

% print(gcf,'saved.png','-dpng')

% set(gcf, 'PaperUnits', 'inches');
% x_width=7.25 ;y_width=9.125
% set(gcf, 'PaperPosition', [0 0 x_width y_width]); %
 
% set([load_sono_file h_trace_line  h_brush h_get h_save_anal],'Visible','off')
% h_tmp=gcf
% set(h_tmp, 'Units', 'Inches', 'Position', [0, 0, 10, 10], 'PaperUnits', 'Inches', 'PaperSize', [10, 10])
% set(h_tmp, 'Units', 'Inches', 'Position', [0, 0, 10, 10], 'PaperUnits', 'Inches', 'PaperSize', [10, 10])
% saveas(h_tmp,'fig1.pdf')
 

% set([load_sono_file h_trace_line  h_brush h_get h_save_anal],'Visible','on')
  
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%SELECT%%
function brush_Callback(source,eventdata)
% set(h_trace_axes,'brush','on')
 hh_brush=brush; %(h_plot;
 set(hh_brush,'Enable','on','Color',[1 0 0]); %,'Parent',h_trace_line);
% set(hh_brush,'ActionPostCallback',@BrushAction );
% get(h_plot)
end

%%SIMPLE%%
function BrushAction(source,eventdata)

% bb = findall(hh_brush,'Tag','Brushing')
  get(h_plot)
%  bb = findobj('Tag','Brushing')
  brush_tmp = get(h_plot,'BrushData');

  firstIndex_brush = find(brush_tmp, 1, 'first');

  XX_tmp = get(h_plot,'XData');
  YY_tmp = get(h_plot,'YData');

  XX = XX_tmp(logical(brush_tmp));
  YY = YY_tmp(logical(brush_tmp));

  x_ip = linspace(XX(1),XX(length(XX)),100);
  y_ip = interp1(XX,YY,x_ip,'spline');

  [maxValue,max_loc]=max(y_ip);
  aboveHalfMax = y_ip > maxValue/2;

  firstIndex = find(aboveHalfMax, 1, 'first');
  lastIndex = find(aboveHalfMax, 1, 'last');

%  set(h_line_scan,'Visible','off')
%  set(h_plot,'Hold','on');
%  hold on;
  line([x_ip(firstIndex) x_ip(firstIndex)], [0 maxValue/2], 'Color', 'g', 'LineWidth', 2);
  line([x_ip(lastIndex) x_ip(lastIndex)], [0 maxValue/2], 'Color', 'g', 'LineWidth', 2);
  line([x_ip(firstIndex) x_ip(lastIndex)], [maxValue/2 maxValue/2], 'Color', 'g', 'LineWidth', 2);
  line([x_ip(max_loc) x_ip(max_loc)], [0 maxValue], 'Color', [0.721569  0.525490  0.043137], 'LineWidth', 2);
  PEAK_INDEX = PEAK_INDEX + 1;
  fwhm = -x_ip(firstIndex)+x_ip(lastIndex);
  text((x_ip(firstIndex)+x_ip(lastIndex))/2, maxValue + 50 , sprintf('Feature: %d\nMax:%.2f\nFWHM=%.2f mm',PEAK_INDEX,maxValue,fwhm),'BackgroundColor',[.7 .9 .7], 'HorizontalAlignment', 'Center') 
 
% XX=XX_tmp(isfinite(XX_tmp))
% YY_tmp = get(bb,'XData' );
% YY=YY_tmp(isfinite(XX_tmp))

% fprintf('Finished\n');
% size(eventdata)
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%SCAN%%
function trace_line_Callback(source,eventdata)
 if FILE_LOADED == true
   imshow(I,'Parent',h_axes);
   hold off;
%  [x,y] = ginput(2);
  [x1,y1] = ginput(1);
  rectangle('Position',[x1-5,y1-5,10,10],'Parent',h_axes,'EdgeColor','r');
%  plot([x1,y1],'Parent',h_axes)
%  set(hm,'MarkerSize',10,'MarkerEdgeColor','w','MarkerFaceColor','m');  
%  plot([x1,y1],'Parent',h_axes,'Color','b','Symbol','x');
  [x2,y2] = ginput(1);
  rectangle('Position',[x2-5,y2-5,10,10],'Parent',h_axes,'EdgeColor','r');
 % h = imdistline(I,[x1,y1],[x2,y2]);
  xline = [x1, x2];
  yline = [y1, y2];
  [CX,CY,C]  = improfile(I,xline, yline);
  ref_distance= sqrt((CX-CX(1)).^2+(CY-CY(1)).^2)*dx_pixel;
  XX_global = ref_distance;
  YY_global = C;
  h_plot = plot(ref_distance,C,'Parent',h_trace_axes);
  xlabel(h_trace_axes,'Distance [mm]');
%  addlistener(h_plot,'YData','PostSet',@(s,e)disp('Data changed'));

  h_line_scan =  line(xline,yline,'Parent',h_axes,'Color','r','LineWidth',2);
%  get(h_line_scan)
 else
  fprintf('Load file!\n');
 end
%  hold off;
end 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%LOAD IMIGE%%
function load_sono_Callback(source,eventdata)
  [file_name, path_name] = uigetfile({'*.jpg;','All jpg files';'*.*',...
                                    'All Files (*.*)'},'Pick an image file');
%  hold on;
  IRGB=imread(strcat(path_name,file_name));
  IBW = rgb2gray(IRGB);
%  I2 = imcomplement(IBW);
  I = imcrop(IBW,[60 85 725 600]);
  imshow(I,'Parent',h_axes);
  cla(h_trace_axes); % celar axes for scan plot

 
% Determine the scale (assume that minor tics on the displayed scale are mm)
  xline = [2, 720]; % set trace line alog the scale
  yline = [595, 595];
  [CX,CY,C]  = improfile(I,xline, yline);
  ref_distance= sqrt((CX-CX(1)).^2+(CY-CY(1)).^2);
%  h_plot = plot(ref_distance,C,'Parent',h_trace_axes);
%  h_line_scan =  line(xline,yline,'Parent',h_axes,'Color','r','LineWidth',2);
  [maxValue,max_loc]=max(C);
  aboveHalfMax = C > maxValue/2;
  firstIndex = find(aboveHalfMax, 1, 'first');
  lastIndex = find(aboveHalfMax, 1, 'last');
%  CX(lastIndex)-CX(firstIndex)
  dx_pixel = (sum(aboveHalfMax)-1)*5/(CX(lastIndex)-CX(firstIndex));
 %  sum(aboveHalfMax)
  


  FILE_LOADED = true;
end

end
