function scarpdater_gui(functioncall)

if(nargin >= 1)
  switch functioncall
    case 'file_quit'
      answer = questdlg('Really quit Scarp Dater?','','Yes','No','No');
      if(strcmp(answer,'Yes'))
        mainfig = FigHandle;
        delete(mainfig);
      end

    case 'file_new'
    answer = questdlg('Really clear all variables?','','Yes','No','No');
    if(strcmp(answer,'Yes'))
      mainfig = FigHandle;
      delete(mainfig)
      clear
      scarpdater_gui
    end

  case 'file_open'
    variableload;

  case 'file_save'
    variablesave;

  case 'file_importoptions'
    changeimportoptions;

  case 'import_importgsi'
     importgsifile;
     
  case 'import_importxz'
     importxz;
     
  case 'import_importtst'
     importtstfile;
     
  case 'edit_offset'
     offsetdata;
     
  case 'offset_quit'
     offset_quit;
     
  case 'offset_refresh'
     offset_refresh;
     
  case 'offset_changea'
     offset_changea;
     
  case 'offset_changeb'
     offset_changeb;
     
  case 'offset_flip'
     offset_flip;
     
  case 'offset_center'
     offset_center;
     
  case 'calculate_finite'
     calculate_finite;
     
  case 'finitequerry_quit'
     finitequerry_quit;
     
  case 'finitequerry_changektmin'
     finitequerry_changektmin;
     
  case 'finitequerry_changektmax'
     finitequerry_changektmax;
     
  case 'finitequerry_changektn'
     finitequerry_changektn;
     
  case 'finitequerry_changebmin'
     finitequerry_changebmin;
     
  case 'finitequerry_changebmax'
     finitequerry_changebmax;
     
  case 'finitequerry_changebn'
     finitequerry_changebn;
     
  case 'finitequerry_changeoffsetmin'
     finitequerry_changeoffsetmin;
     
  case 'finitequerry_changeoffsetmax'
     finitequerry_changeoffsetmax;
     
  case 'finitequerry_changeoffsetn'
     finitequerry_changeoffsetn;
     
  case 'finitequerry_changea'
     finitequerry_changea;
     
  case 'finitequerry_changetheta'
     finitequerry_changetheta;
     
  case 'finitequerry_changeoffsetscale'
     finitequerry_changeoffsetscale;
     
  case 'finitequerry_OK'
     finitequerry_OK;
     
  case 'plot_RMSContours'
     plot_RMSContours;
     
  case 'plot_RMSContours_quit'
     plot_RMSContours_quit;
     
  case 'plot_changeRMSContour'
     plot_changeRMSContour;
     
  case 'plot_RMSIsosurfaces'
     plot_RMSIsosurfaces;
     
  case 'plot_RMSIsosurfaces_quit'
     plot_RMSIsosurfaces_quit;
     
  case 'plot_RMSIsosurfaces_axisequal'
     plot_RMSIsosurfaces_axisequal;
     
  case 'plot_RMSIsosurfaces_axisnormal'
     plot_RMSIsosurfaces_axisnormal;

  case 'plot_RMSIsosurfaces_clearfig'
     plot_RMSIsosurfaces_clearfig;
     
  case 'plot_RMSIsosurfaces_addisosurface'
     plot_RMSIsosurfaces_addisosurface;
     
  case 'boxcancel'
     boxcancel;
     
  case 'boxedit'
     boxedit;
     
  case 'boxOK'
     boxOK;
     
  case 'plot_forwardmodels'
     plot_forwardmodels;
     
  case 'plot_sensitivityanalysis'
     plot_sensitivityanalysis;
     
  case 'plot_sensitivityanalysis_quit'
     plot_sensitivityanalysis_quit;
     
  % Ramon's callbacks:
     
   case 'defaults'
       defaults
      
   case 'EditBoxReturn_a'
       EditBoxReturn_a;
       
    case 'EditBoxReturn_b'
       EditBoxReturn_b;

	 case 'EditBoxReturn_theta'
       EditBoxReturn_theta
       
    case 'EditBoxReturn_kt'
       EditBoxReturn_kt
       
	 case 'EditBoxReturn_xmin'
       EditBoxReturn_xmin
       
    case 'EditBoxReturn_xmax'
   	 EditBoxReturn_xmax

    case 'EditBoxReturn_dx'
       EditBoxReturn_dx
       
 	 case 'finitescarp'
        finitescarp
       
 	 case 'plotfinitescarp'
    	  plotfinitescarp
         
    case 'holdcontrol'
       holdcontrol
    case 'axiscontrol'
       axiscontrol
    case 'plotdata'
       plotdata

     
  otherwise
    error('Unrecognized function call.');
  end

else
  mainfig = create_gui;
  set(mainfig,'Visible','on')
  drawnow
end

%-----------------------------
function mainfig = FigHandle

mainfig = findobj(allchild(0),'Tag','ScarpDater_Figure');

%-----------------------------
function offsetfig = OffsetFigHandle

offsetfig = findobj(allchild(0),'Tag','Offset_Figure');

%-----------------------------
function finitequerryfig = FiniteQuerryHandle

finitequerryfig = findobj(allchild(0),'Tag','FiniteQuerry_Figure');

%-----------------------------
function RMSContoursFig = RMSContoursHandle

RMSContoursFig = findobj(allchild(0),'Tag','RMSContours_Figure');

%-----------------------------
function RMSIsosurfacesFig = RMSIsosurfacesHandle

RMSIsosurfacesFig = findobj(allchild(0),'Tag','RMSIsosurfaces_Figure');

%-----------------------------
function mainfig = create_gui

mainfig = figure('Position',[20 20 600 600],'CloseRequestFcn', ...
   'scarpdater_gui file_quit','Resize','on','menubar','none','Visible','off', ...
   'NumberTitle','off','Name','Diffusion Scarp Dater','Units','pixels', ...
   'Color',[1 1 1],'Colormap',gray(256),'Tag','ScarpDater_Figure');

create_menus(mainfig);
set_initialvalues(mainfig);
create_guiobjects(mainfig);

%-----------------------------
function create_menus(mainfig)

mFile = uimenu('parent',mainfig,'label','&File');
mEdit = uimenu('parent',mainfig,'label','&Edit');
mCalculate = uimenu('parent',mainfig,'label','&Calculate');
mPlot = uimenu('parent',mainfig,'label','&Plot');

% File menu:

uimenu('parent',mFile,'label','&New','Callback','scarpdater_gui file_new');
uimenu('parent',mFile,'label','&Open...','Callback','scarpdater_gui file_open');
uimenu('parent',mFile,'label','&Save As...','Callback','scarpdater_gui file_save');
uimenu('parent',mFile,'label','GSI Import O&ptions...','callback','scarpdater_gui file_importoptions','separator','on');
Import = uimenu('parent',mFile,'label','Import');
uimenu('parent',mFile,'label','&Quit','Callback','scarpdater_gui file_quit', ...
   'separator','on');

% Import submenu:

uimenu('parent',Import,'label','Total Station File...','callback','scarpdater_gui import_importgsi');
uimenu('parent',Import,'label','Text X-Z format...','callback','scarpdater_gui import_importxz');
uimenu('parent',Import,'label','TST Profile File...','callback','scarpdater_gui import_importtst')

% Edit menu:

parameters.menus.offset = uimenu('parent',mEdit,'label', ...
   'Offset data...', ...
   'Callback','scarpdater_gui edit_offset','enable','off');

% Calculate menu:

parameters.menus.calcfinite = uimenu('parent',mCalculate,'label','Calculate &Finite-Scarp RMS...','callback', ...
   'scarpdater_gui calculate_finite','enable','off');
%parameters.menus.calccs = uimenu('parent',mCalculate,'label','Calculate &Continuous-slip RMS...','callback', ...
%   'scarpdater_gui calculate_continuous','enable','off');

% Plot menu:
parameters.menus.plotforwardmodels = uimenu('parent',mPlot,'label','Plot Single-Event &Forward Models...',...
   'callback','scarpdater_gui plot_forwardmodels','enable','on');
parameters.menus.plotRMSContours = uimenu('parent',mPlot,'label','Plot Single-Event RMS &Contours...',...
   'callback','scarpdater_gui plot_RMSContours','enable','off','separator','on');
parameters.menus.plotRMSIsosurfaces = uimenu('parent',mPlot,'label','Plot Single-Event RMS &Isosurfaces...',...
   'callback','scarpdater_gui plot_RMSIsosurfaces','enable','off');
parameters.menus.plotSensitivityAnalysis = uimenu('parent',mPlot,'label',...
   'Plot Single-Event &Sensitivity Analysis...','callback','scarpdater_gui plot_sensitivityanalysis',...
   'separator','on','enable','off');


parameters.menus.mEdit = mEdit;
parameters.menus.mFile = mFile;
parameters.menus.mCalculate = mCalculate;
parameters.menus.mPlot = mPlot;

set(mainfig,'UserData',parameters);

%-----------------------------
function create_guiobjects(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
white = [1 1 1];
title=uicontrol('Parent',mainfig,'Style','text','String', ...
   'Diffusion Scarp Dater','Position',[50 560 500 40],'BackgroundColor', ...
   [1 1 1],'FontSize',24,'FontWeight','bold');
authors=uicontrol('Parent',mainfig,'Style','text','String', ...
   'written by George Hilley', ...
   'Position',[150 540 300 20],'BackgroundColor', [1 1 1],'FontSize',12);
Potsdam=uicontrol('Parent',mainfig,'Style','text','String', ...
   'Universitaet Potsdam','Position',[100 520 400 20], ...
   'BackgroundColor',[1 1 1],'FontSize',12,'FontAngle','italic');
copyright=uicontrol('Parent',mainfig,'Style','text','String', ...
   '(C) 2002','Position',[100 500 400 20],'BackgroundColor', ...
   white,'FontSize',12,'FontAngle','italic');

parameters.data_axes = axes('Parent',mainfig,...
             'box','on', ...
             'Units','pixels','Position',[100 50 400 400]);

xlabel('Easting (m)');
ylabel('Northing (m)');

set(mainfig,'UserData',parameters,'HandleVisibility','callback');



%---------------------
function set_initialvalues(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
parameters.formatstruct = scarpdater_defaultformatstruct;
data.exists = 0;
data.x = [];
data.z = [];
singleevent.calc = 0;
singleevent.RMS = [];
singleevent.ktvec = [];
singleevent.offsetvec = [];
singleevent.bvec = [];
singleevent.a = 0;
singleevent.theta = 0;
singleevent.bestkt = 0;
singleevent.bestoffset = 0;
singleevent.bestb = 0;
continuous.calc = 0;
continuous.RMS = [];
continuous.ktvec = [];
continuous.offsetvec = [];
continuous.bvec = [];
continuous.a = 0;
continuous.bestkt = 0;
continuous.bestoffset = 0;
continuous.bestb = 0;
parameters.data = data;
parameters.analysis.singleevent = singleevent;
parameters.analysis.continuous = continuous;
set(mainfig,'UserData',parameters);

%----------------------
function variableload(mainfig)
mainfig = FigHandle;
filename = uigetfile('*.mat','Scarp Dater file to open...');
if(filename ~= 0)
  load(filename)
  if(ScarpDaterFile == 1)
    parameters = get(mainfig,'UserData');
    parameters.data = data;
    parameters.analysis = analysis;
    parameters.formatstruct = formatstruct;
    if(parameters.data.exists == 1)
       set(parameters.menus.offset,'enable','on');
       set(parameters.menus.calcfinite,'enable','on');
       set(parameters.menus.calccs,'enable','on');
    end
    
    
    set(mainfig,'UserData',parameters);
    refreshfigure(mainfig);
  else
    errordlg(strcat(filename,' is not a valid Scarp Dater input file.'), ...
      'Open Error');
  end
end

%----------------------
function variablesave(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
filename = uiputfile('*.mat','Scarp Dater file to save...');

if(filename ~= 0)
  data = parameters.data;
  analysis = parameters.analysis;
  formatstruct = parameters.formatstruct;
  ScarpDaterFile = 1;

  clear parameters;
  clear mainfig;
  save(filename);
end


%----------------------
function importgsifile(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');

filename = uigetfile('*');
if(filename ~= 0)
  formatstruct = parameters.formatstruct;
  data = scarpdater_readgsifile(filename,formatstruct);
  data.exists = 1;
  parameters.data = data;
  set(parameters.menus.offset,'enable','on');
  set(parameters.menus.calcfinite,'enable','on');
  set(parameters.menus.calccs,'enable','on');
  refreshfigure(mainfig);
end

set(mainfig,'UserData',parameters);

%----------------------
function importtst(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');

filename = uigetfile('*.mat');
if(filename ~= 0)
  load(filename);
  newdata.x = data.E;
  newdata.z = data.N;
  data = newdata;
  data.exists = 1;
  parameters.data = data;
  set(parameters.menus.offset,'enable','on');
  set(parameters.menus.calcfinite,'enable','on');
  set(parameters.menus.calccs,'enable','on');
  set(mainfig,'UserData',parameters);
  refreshfigure(mainfig);
end


%----------------------
function importxz(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');

filename = uigetfile('*.mat');
if(filename ~= 0)
   fid = fopen(filename,'r');
   counter = 1;
   while(~feof(fid))
      line = fgetl(fid);
      numbers = sscanf(line,'%f  %f');
      if(length(numbers) == 2)
         data.x(counter) = numbers(1);
         data.z(counter) = numbers(2);
         counter = counter + 1;
      end
   end   
   data.exists = 1;
   parameters.data = data;
   set(parameters.menus.offset,'enable','on');
   set(parameters.menus.calcfinite,'enable','on');
 %  set(parameters.menus.calc,'enable','on');
   set(mainfig,'UserData',parameters);
   refreshfigure(mainfig);
end



%------------------------
function changeimportoptions(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');

prompt = {'Point ID : ','Description : ','Northing Code : ','Easting Code : ','Elevation Code: '};
def = {num2str(parameters.formatstruct.Pt_code),parameters.formatstruct.description{1},num2str(parameters.formatstruct.NorthingCode),num2str(parameters.formatstruct.EastingCode),num2str(parameters.formatstruct.ElevationCode)};
dlgTitle = 'Change Import Options';
answer = inputdlg(prompt,dlgTitle,1,def);
if(~isempty(answer))
  parameters.formatstruct.Pt_code = str2num(answer{1});
  parameters.formatstruct.description = answer{2};
  parameters.formatstruct.NorthingCode = str2num(answer{3});
  parameters.formatstruct.EastingCode = str2num(answer{4});
  parameters.formatstruct.ElevationCode = str2num(answer{5});
end

set(mainfig,'UserData',parameters);  



%---------------------------
function refreshfigure(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
axes(parameters.data_axes);
plot(parameters.data.x,parameters.data.z,'k.');
xlabel('Distance along Profile');
ylabel('Elevation of Profile');


%----------------------------
function offsetdata

turnmainmenusoff;

mainfig = FigHandle;
parameters = get(mainfig,'UserData');

offsetfig = figure('Position',[100 100 600 500],'CloseRequestFcn', ...
   'scarpdater_gui offset_quit','Resize','on','Visible','on', ...
   'NumberTitle','off','Name','Profile Offset Adjustment Tool','Units','pixels', ...
   'Colormap',gray(256),'Tag','Offset_Figure');


parameters_offset.data_axes = axes('Parent',offsetfig,...
             'box','on', ...
             'Units','pixels','Position',[50 50 400 400]);
          
parameters_offset.a = 10;
parameters_offset.b = 0;

c = get(offsetfig,'color');

parameters_offset.title = uicontrol('style','text','position',[75 450 300 40],...
   'HorizontalAlign','center','FontSize',18,'String',...
   'Offset Profile Correction','backgroundcolor',c);
parameters_offset.text = uicontrol('style','text','position',[470 450 100 30],...
   'HorizontalAlignment','left','fontsize',14,'string','Parameters:','backgroundcolor',c);
parameters_offset.text1 = uicontrol('style','text','position',[470 400 30 20],'string','a =',...
   'backgroundcolor',c);
parameters_offset.text1 = uicontrol('style','text','position',[470 380 30 20],'string','b =',...
   'backgroundcolor',c);
parameters_offset.abox = uicontrol('style','edit','position',[520 400 60 20],'string',...
   num2str(parameters_offset.a),'callback','scarpdater_gui offset_changea');
parameters_offset.bbox = uicontrol('style','edit','position',[520 380 60 20],'string',...
   num2str(parameters_offset.b),'callback','scarpdater_gui offset_changeb');
parameters_offset.axistext = uicontrol('style','text','position',[470 340 100 20],'string',...
   'Axis Scaling:','horizontalalignment','left','backgroundcolor',c);
parameters_offset.axisscale = uicontrol('style','popupmenu','string',{'Normal' 'Equal'},'value',...
   1,'callback','scarpdater_gui offset_refresh','position',[490 300 100 20]);

parameters_offset.flipbutton = uicontrol('style','pushbutton','position',[490 250 100 20],'string',...
   'Flip Profile','backgroundcolor',c,'callback','scarpdater_gui offset_flip');
parameters_offset.centerbutton = uicontrol('style','pushbutton','position',[490 230 100 20],...
   'string','Center','fontweight','bold','backgroundcolor',c,'callback',...
   'scarpdater_gui offset_center');

          
set(offsetfig,'UserData',parameters_offset);
offset_refresh;

%--------
function offset_changea

offsetfig = OffsetFigHandle;
parameters_offset = get(offsetfig,'UserData');
newstr = get(parameters_offset.abox,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if(newval > 0)
      parameters_offset.a = newval;
      set(offsetfig,'userdata',parameters_offset);
      offset_refresh;
   end
end

set(parameters_offset.abox,'string',num2str(parameters_offset.a));

%--------
function offset_changeb

offsetfig = OffsetFigHandle;
parameters_offset = get(offsetfig,'UserData');
newstr = get(parameters_offset.bbox,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if(abs(newval <= 90))
      parameters_offset.b = newval;
      set(offsetfig,'userdata',parameters_offset);
      offset_refresh;
   end
end

set(parameters_offset.bbox,'string',num2str(parameters_offset.b));

%--------
function offset_flip

mainfig = FigHandle;
parameters = get(mainfig,'userdata');
parameters.data.x = -parameters.data.x;
set(mainfig,'userdata',parameters);
offset_refresh;

%--------
function offset_center

[offx,offz] = ginput(1);
mainfig = FigHandle;
parameters = get(mainfig,'userdata');
parameters.data.x = parameters.data.x - offx;
parameters.data.z = parameters.data.z - offz;
set(mainfig,'userdata',parameters);
offset_refresh;


%--------
function offset_quit

offsetfig = OffsetFigHandle;
delete(offsetfig);
turnmainmenuson
refreshfigure;

%--------
function offset_refresh

mainfig = FigHandle;
offsetfig = OffsetFigHandle;
parameters_offset = get(offsetfig,'UserData');
axes(parameters_offset.data_axes);
parameters = get(mainfig,'UserData');
plot(parameters.data.x,parameters.data.z,'k.')
hold on
minx = min(parameters.data.x);
maxx = max(parameters.data.x);
if(minx > 0)
   minx = -5;
end

if(maxx < 0)
   maxx = 5;
end

a = parameters_offset.a;
amin = -(parameters_offset.b*pi/180)*minx + a;
amax = -(parameters_offset.b*pi/180)*maxx - a;
plot([minx 0],[amin a],'k--');
plot([0 maxx],[-a amax],'k--');
val = get(parameters_offset.axisscale,'value');
if(val == 1)
  maxy = max([parameters.data.z amax amin]);
  miny = min([parameters.data.z amax amin]);
  axis([minx maxx 1.1*miny 1.1*maxy])
else
   axis equal
end
hold off
xlabel('Distance Along Profile');
ylabel('Elevation');

%-------
function calculate_finite

turnmainmenusoff

FiniteQuerryFig = figure('Position',[200 200 450 450],'CloseRequestFcn', ...
   'scarpdater_gui finitequerry_quit','Resize','on','Visible','on', ...
   'NumberTitle','off','Name','Finite Scarp RMS Calculation','Units','pixels', ...
   'Colormap',gray(256),'Tag','FiniteQuerry_Figure','menubar','none');

c = get(FiniteQuerryFig,'color');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',14,'position',[90 415 350 30],...
   'string','Single Event Scarp Parameters','backgroundcolor',c,'HorizontalAlignment','left');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',10,'fontweight','bold','string',...
   'Morphologic Age (kt)','position',[10 350 200 20],'backgroundcolor',c,'HorizontalAlignment','left');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',10,'fontweight','bold','string',...
   'Fan Slope (b) [deg]','position',[10 250 150 20],'backgroundcolor',c,'HorizontalAlignment','left');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',10,'fontweight','bold','string',...
   'Hz Offset (O) ','position',[10 150 200 20],'backgroundcolor',c,'HorizontalAlignment','left');

uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','kt min =','position',...
   [30 320 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','kt max =','position',...
   [30 300 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','n =','position',...
   [30 280 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','b min =','position',...
   [30 220 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','b max =','position',...
   [30 200 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','n =','position',...
   [30 180 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','off. min =','position',...
   [30 120 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','off. max =','position',...
   [30 100 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','n =','position',...
   [30 80 50 20],'backgroundcolor',c,'horizontalalignment','right');

kt.min = 0;
kt.max = 300;
kt.n = 31;

b.min = 0;
b.max = 4;
b.n = 31;

offset.min = -5;
offset.max = 5;
offset.n = 31;

a = 5;
theta = 45;

parameters.kt = kt;
parameters.b = b;
parameters.offset = offset;
parameters.a = a;
parameters.theta = theta;

controls.ktmin = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(kt.min),'position',...
   [100 320 50 20],'callback','scarpdater_gui finitequerry_changektmin');
controls.ktmax = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(kt.max),'position',...
   [100 300 50 20],'callback','scarpdater_gui finitequerry_changektmax');
controls.ktn = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(kt.n),'position',...
   [100 280 50 20],'callback','scarpdater_gui finitequerry_changektn');

controls.bmin = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(b.min),'position',...
   [100 220 50 20],'callback','scarpdater_gui finitequerry_changebmin');
controls.bmax = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(b.max),'position',...
   [100 200 50 20],'callback','scarpdater_gui finitequerry_changebmax');
controls.bn = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(b.n),'position',...
   [100 180 50 20],'callback','scarpdater_gui finitequerry_changebn');

controls.offsetmin = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(offset.min),'position',...
   [100 120 50 20],'callback','scarpdater_gui finitequerry_changeoffsetmin');
controls.offsetmax = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(offset.max),'position',...
   [100 100 50 20],'callback','scarpdater_gui finitequerry_changeoffsetmax');
controls.offsetn = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(offset.n),'position',...
   [100 80 50 20],'callback','scarpdater_gui finitequerry_changeoffsetn');

controls.ktscale = uicontrol('parent',FiniteQuerryFig,'style','popupmenu','string',...
   {'Linear' 'Logarithmic'},'position',[200 300 100 20]);
controls.bscale = uicontrol('parent',FiniteQuerryFig,'style','popupmenu','string',...
   {'Linear' 'Logarithmic'},'position',[200 200 100 20]);
controls.offsetscale = uicontrol('parent',FiniteQuerryFig,'style','popupmenu','string',...
   {'Linear' 'Logarithmic'},'position',[200 100 100 20],'callback','scarpdater_gui finitequerry_changeoffsetscale');

uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','a =','position',...
   [300 250 50 20],'backgroundcolor',c,'horizontalalignment','right');
uicontrol('parent',FiniteQuerryFig,'style','text','fontsize',8,'string','theta =','position',...
   [300 150 50 20],'backgroundcolor',c,'horizontalalignment','right');

controls.a = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(a),...
   'position',[370 250 50 20],'callback','scarpdater_gui finitequerry_changea');
controls.theta = uicontrol('parent',FiniteQuerryFig,'style','edit','string',num2str(theta),...
   'position',[370 150 50 20],'callback','scarpdater_gui finitequerry_changetheta');
controls.OK = uicontrol('parent',FiniteQuerryFig,'style','pushbutton','string','OK','callback',...
   'scarpdater_gui finitequerry_OK','position',[350 25 40 20]);
controls.cancel = uicontrol('parent',FiniteQuerryFig,'style','pushbutton','string','Cancel',...
   'callback','scarpdater_gui finitequerry_quit','position',[270 25 40 20]);

out.controls = controls;
out.parameters = parameters;

set(FiniteQuerryFig,'UserData',out);

%-------
function finitequerry_changektmin

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.ktmin,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if((newval > 0) & (newval < in.parameters.kt.max))
      in.parameters.kt.min = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.ktmin,'string',num2str(in.parameters.kt.min));

%-------
function finitequerry_changektmax 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.ktmax,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if(newval > in.parameters.kt.min)
      in.parameters.kt.max = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.ktmax,'string',num2str(in.parameters.kt.max));

%-------
function finitequerry_changektn 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.ktn,'string');
newval = str2num(newstr);

if(~isempty(newval))
   newval = round(newval);
   if(newval > 0)
      in.parameters.kt.n = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.ktn,'string',num2str(in.parameters.kt.n));

%-------
function finitequerry_changebmin

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.bmin,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if((newval > 0) & (newval < in.parameters.b.max))
      in.parameters.b.min = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.bmin,'string',num2str(in.parameters.b.min));

%-------
function finitequerry_changebmax 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.bmax,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if(newval > in.parameters.b.min)
      in.parameters.b.max = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.bmax,'string',num2str(in.parameters.b.max));

%-------
function finitequerry_changebn 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.bn,'string');
newval = str2num(newstr);

if(~isempty(newval))
   newval = round(newval);
   if(newval > 0)
      in.parameters.b.n = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.bn,'string',num2str(in.parameters.b.n));


%-------
function finitequerry_changeoffsetmin

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.offsetmin,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if((get(in.controls.offsetscale,'value') == 2) & (newval < 0))
      newval = 0;
   end
   
   if((newval < in.parameters.offset.max))
      in.parameters.offset.min = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.offsetmin,'string',num2str(in.parameters.offset.min));

%-------
function finitequerry_changeoffsetmax 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.offsetmax,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if((get(in.controls.offsetscale,'value') == 2) & (newval < 0))
      newval = 0;
   end   
   
   if(newval > in.parameters.offset.min)
      in.parameters.offset.max = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.offsetmax,'string',num2str(in.parameters.offset.max));

%-------
function finitequerry_changeoffsetn 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.offsetn,'string');
newval = str2num(newstr);

if(~isempty(newval))
   newval = round(newval);
   if(newval > 0)
      in.parameters.offset.n = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.offsetn,'string',num2str(in.parameters.offset.n));

%-------
function finitequerry_changea 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.a,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if(newval > 0)
      in.parameters.a = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.a,'string',num2str(in.parameters.a));

%-------
function finitequerry_changetheta 

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

newstr = get(in.controls.theta,'string');
newval = str2num(newstr);

if(~isempty(newval))
   if(newval > 0)
      if(newval > 75)
         newval = 90;
      end
      
      in.parameters.theta = newval;
      set(FiniteQuerryFig,'userdata',in);
   end
end

set(in.controls.theta,'string',num2str(in.parameters.theta));

%-------
function finitequerry_changeoffsetscale

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'userdata');

val = get(in.controls.offsetscale,'value');
if(val == 2)
   if(in.parameters.offset.min < 0)
      in.parameters.offset.min = 0;
   end
   if(in.parameters.offset.max < 0)
      in.parameters.offset.max = 1;
   end
end
set(FiniteQuerryFig,'Userdata',in);
set(in.controls.offsetmin,'string',num2str(in.parameters.offset.min));
set(in.controls.offsetmax,'string',num2str(in.parameters.offset.max));

%-------
function finitequerry_OK

FiniteQuerryFig = FiniteQuerryHandle;
in = get(FiniteQuerryFig,'UserData');

a = in.parameters.a
theta = in.parameters.theta;

if(get(in.controls.ktscale,'value') == 1)
   inc = (in.parameters.kt.max - in.parameters.kt.min)/in.parameters.kt.n;
   ktvec = in.parameters.kt.min:inc:in.parameters.kt.max;
else
   inc = (log10(in.parameters.kt.max) - log10(in.parameters.kt.min))/in.parameters.kt.n;
   ktvec = 10.^[log10(in.parameters.kt.min):inc:log10(in.parameters.kt.max)];
end

if(get(in.controls.bscale,'value') == 1)
   inc = (in.parameters.b.max - in.parameters.b.min)/in.parameters.b.n;
   bvec = in.parameters.b.min:inc:in.parameters.b.max;
else
   inc = (log10(in.parameters.b.max) - log10(in.parameters.b.min))/in.parameters.b.n;
   bvec = 10.^[log10(in.parameters.b.min):inc:log10(in.parameters.b.max)];
end

if(get(in.controls.offsetscale,'value') == 1)
   inc = (in.parameters.offset.max - in.parameters.offset.min)/in.parameters.offset.n;
   offsetvec = in.parameters.offset.min:inc:in.parameters.offset.max;
else
   inc = (log10(in.parameters.offset.max) - log10(in.parameters.offset.min))/in.parameters.offset.n;
   offsetvec = 10.^[log10(in.parameters.offset.min):inc:log10(in.parameters.offset.max)];
end

mainfig = FigHandle;
parameters = get(mainfig,'UserData');

parameters.analysis.singleevent.ktvec = ktvec;
parameters.analysis.singleevent.bvec = bvec;
parameters.analysis.singleevent.offsetvec = offsetvec;

a = in.parameters.a;
theta = in.parameters.theta;

box = dialog('position',[400 300 200 30]);
uicontrol('style','text','string','Calculating RMS, please wait...','parent',box,'position',...
   [10 5 150 20]);
drawnow;
delete(FiniteQuerryFig);


RMS = scarpdater_finitescarperror(parameters.data.x,parameters.data.z,theta,...
   a,ktvec,bvec,offsetvec);

delete(box)

[bestkt,bestb,bestoffset] = scarpdater_findminRMS(ktvec,bvec,offsetvec,RMS);

parameters.analysis.singleevent.bestkt = bestkt;
parameters.analysis.singleevent.bestb = bestb;
parameters.analysis.singleevent.bestoffset = bestoffset;
parameters.analysis.singleevent.RMS = RMS;
parameters.analysis.singleevent.a = a;
parameters.analysis.singleevent.theta = theta;
parameters.analysis.singleevent.done = 1;

set(mainfig,'userdata',parameters);

box = dialog('position',[400 300 200 300]);
uicontrol('style','text','string','Best Fit Parameters:','parent',box,'position',...
   [10 210 175 80],'fontsize',14,'fontweight','bold');
uicontrol('style','text','string','a =','parent',box,'position',...
   [30 200 50 20],'horizontalalignment','right');
uicontrol('style','text','string','b =','parent',box,'position',...
   [30 180 50 20],'horizontalalignment','right');
uicontrol('style','text','string','theta =','parent',box,'position',...
   [30 160 50 20],'horizontalalignment','right');
uicontrol('style','text','string','kt =','parent',box,'position',...
   [30 140 50 20],'horizontalalignment','right');
uicontrol('style','text','string','offset =','parent',box,'position',...
   [30 120 50 20],'horizontalalignment','right');

uicontrol('style','text','string',num2str(round(a*100)/100),'parent',box,'position',...
   [100 200 50 20],'horizontalalignment','left');
uicontrol('style','text','string',num2str(round(bestb*100)/100),'parent',box,'position',...
   [100 180 50 20],'horizontalalignment','left');
uicontrol('style','text','string',num2str(round(theta*100)/100),'parent',box,'position',...
   [100 160 50 20],'horizontalalignment','left');
uicontrol('style','text','string',num2str(round(bestkt*100)/100),'parent',box,'position',...
   [100 140 50 20],'horizontalalignment','left');
uicontrol('style','text','string',num2str(round(bestoffset*100)/100),'parent',box,'position',...
   [100 120 50 20],'horizontalalignment','left');

uicontrol('style','pushbutton','string','OK','position',[90 50 30 20],'callback','delete(gcf)');

turnmainmenuson;
activateRMSplotmenus;

%-------
function finitequerry_quit

FiniteQuerryFig = FiniteQuerryHandle;
delete(FiniteQuerryFig);
turnmainmenuson;

%-------
function plot_RMSContours

turnmainmenusoff

mainfig = FigHandle;
parameters = get(mainfig,'userdata');

kt = parameters.analysis.singleevent.ktvec;
b = parameters.analysis.singleevent.bvec;
offset = parameters.analysis.singleevent.offsetvec;
a = parameters.analysis.singleevent.a;
theta = parameters.analysis.singleevent.theta;

RMSContoursFig = figure('CloseRequestFcn','scarpdater_gui plot_RMSContours_quit','position',...
   [200 50 600 600],'Resize','on','Visible','on', ...
   'NumberTitle','off','Name','Single Event Contour Plot','Units','pixels', ...
   'Colormap',gray(256),'Tag','RMSContours_Figure');

c = get(RMSContoursFig,'color');

controls.axes = axes('parent',RMSContoursFig,'units','pixels','position',[50 50 450 450]);

uicontrol('style','text','position',[520 450 80 20],'string','Fixed Dim:','backgroundcolor',...
   c,'fontweight','bold');

controls.fixeddim = uicontrol('style','popupmenu','position',[520 420 80 20],'string',...
   {'kt','b','offset'},'value',1,'callback','scarpdater_gui plot_changeRMSContour');

for(i=1:length(kt))
   ktstr{i} = num2str(kt(i));
end

uicontrol('style','text','position',[520 350 80 20],'string','Fixed Value:','backgroundcolor',...
   c,'fontweight','bold');

controls.fixedval = uicontrol('style','popupmenu','position',[520 320 80 20],'string',...
   ktstr,'callback','scarpdater_gui plot_changeRMSContour');

uicontrol('style','text','position',[520 250 80 20],'string','Contour:','backgroundcolor',c,...
   'fontweight','bold');
uicontrol('style','text','position',[510 200 40 20],'string','min=','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[510 170 40 20],'string','inc=','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[510 140 40 20],'string','max=','horizontalalignment',...
   'right','backgroundcolor',c);
controls.minbox = uicontrol('style','edit','position',[555 200 30 20],'string','0','callback',...
   'scarpdater_gui plot_changeRMSContour');
controls.incbox = uicontrol('style','edit','position',[555 170 30 20],'string','0.2','callback',...
   'scarpdater_gui plot_changeRMSContour');
controls.maxbox = uicontrol('style','edit','position',[555 140 30 20],'string','2','callback',...
   'scarpdater_gui plot_changeRMSContour');

uicontrol('style','text','position',[150 555 300 40],'fontsize',14,'fontweight','bold','string',...
   'Single Event RMS Contour Plot','backgroundcolor',c);
uicontrol('style','text','position',[200 520 40 20],'string','a =','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[200 500 40 20],'string','theta =','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[250 520 40 20],'string',...
   num2str(round(a*100)/100),'horizontalalignment',...
   'left','backgroundcolor',c);
uicontrol('style','text','position',[250 500 40 20],'string',...
   num2str(round(theta*100)/100),'horizontalalignment',...
   'left','backgroundcolor',c);

uicontrol('style','text','position',[300 545 60 20],'string','Best Fit:','horizontalalignment',...
   'left','backgroundcolor',c,'fontweight','bold');
uicontrol('style','text','position',[300 530 40 20],'string','kt =','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[300 515 40 20],'string','b =','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[300 500 40 20],'string','offset =','horizontalalignment',...
   'right','backgroundcolor',c);
uicontrol('style','text','position',[350 530 40 20],'string',...
   num2str(round(parameters.analysis.singleevent.bestkt*100)/100),'horizontalalignment',...
   'left','backgroundcolor',c);
uicontrol('style','text','position',[350 515 40 20],'string',...
   num2str(round(parameters.analysis.singleevent.bestb*100)/100),'horizontalalignment',...
   'left','backgroundcolor',c);
uicontrol('style','text','position',[350 500 40 20],'string',...
   num2str(round(parameters.analysis.singleevent.bestoffset*100)/100),'horizontalalignment',...
   'left','backgroundcolor',c);

controls.min = 0;
controls.inc = 0.2;
controls.max = 2;

set(RMSContoursFig,'userdata',controls);
refreshRMSContourFig;

%-------
function plot_changeRMSContour

RMSContourFig = RMSContoursHandle;
controls = get(RMSContourFig,'userdata');

val = str2num(get(controls.minbox,'string'));
if(~isempty(val))
   if((val < controls.max) & (val >= 0))
      controls.min = val;
   end
end

set(controls.minbox,'string',num2str(controls.min));

val = str2num(get(controls.maxbox,'string'));
if(~isempty(val))
   if((val > controls.min) & (val > 0))
      controls.max = val;
   end
end

set(controls.maxbox,'string',num2str(controls.max));

val = str2num(get(controls.incbox,'string'));
if(~isempty(val))
   if((val < (controls.max - controls.min)) & (val > 0))
      controls.inc = val;
   end
end

set(controls.incbox,'string',num2str(controls.inc));

val = get(controls.fixeddim,'value');

mainfig = FigHandle;
parameters = get(mainfig,'userdata');

ktvec = parameters.analysis.singleevent.ktvec;
bvec = parameters.analysis.singleevent.bvec;
offsetvec = parameters.analysis.singleevent.offsetvec;

switch val
  case 1
     for(i=1:length(ktvec))
        instring{i} = num2str(ktvec(i));
     end
  case 2
     for(i=1:length(bvec))
        instring{i} = num2str(bvec(i));
     end
  case 3
     for(i=1:length(offsetvec))
        instring{i} = num2str(offsetvec(i));
     end
end

set(controls.fixedval,'string',instring);
set(RMSContourFig,'userdata',controls);
refreshRMSContourFig;

%-------
function plot_RMSContours_quit

RMSContourFig = RMSContoursHandle;
delete(RMSContourFig);
turnmainmenuson;

%-------
function plot_RMSIsosurfaces

turnmainmenusoff;

RMSIsosurfacesFig = figure('CloseRequestFcn','scarpdater_gui plot_RMSIsosurfaces_quit','position',...
   [200 50 600 600],'Resize','on','Visible','on', ...
   'NumberTitle','off','Name','Single Event Isosurface Plot','Units','pixels',...
   'Tag','RMSIsosurfaces_Figure');

controls.axes = axes('parent',RMSIsosurfacesFig,'visible','on');
controls.mPlot = uimenu('parent',RMSIsosurfacesFig,'label','&Plot');
controls.mPlotClear = uimenu('parent',controls.mPlot,'label','&Clear Figure','callback',...
   'scarpdater_gui plot_RMSIsosurfaces_clearfig');
controls.mPlotEqual = uimenu('parent',controls.mPlot,'label','Axis &Equal','callback',...
   'scarpdater_gui plot_RMSIsosurfaces_axisequal','separator','on');
controls.mPlotNormal = uimenu('parent',controls.mPlot,'label','Axis &Normal','callback',...
   'scarpdater_gui plot_RMSIsosurfaces_axisnormal','checked','on');
controls.mPlotAdd = uimenu('parent',controls.mPlot,'label','&Add Isosurface','callback',...
   'scarpdater_gui plot_RMSIsosurfaces_addisosurface');

set(RMSIsosurfacesFig,'userdata',controls);
plot_RMSIsosurfaces_clearfig;

%-------
function plot_RMSIsosurfaces_clearfig

RMSIsosurfacesFig = RMSIsosurfacesHandle;
controls = get(RMSIsosurfacesFig,'userdata');
axes(controls.axes);
cla;
axes(controls.axes);

hold on;
mainfig = FigHandle;
parameters = get(mainfig,'userdata');
bestkt = parameters.analysis.singleevent.bestkt;
bestb = parameters.analysis.singleevent.bestb;
bestoffset = parameters.analysis.singleevent.bestoffset;
plot3(bestkt,bestb,bestoffset,'k+');
grid on;
view(3);
hold on;

xlabel('kt');
ylabel('b');
zlabel('offset');
set(controls.mPlotNormal,'checked','on');
set(controls.mPlotEqual,'checked','off');
set(RMSIsosurfacesFig,'userdata',controls);

%-------
function plot_RMSIsosurfaces_quit

RMSIsosurfacesFig = RMSIsosurfacesHandle;
delete(RMSIsosurfacesFig);
turnmainmenuson;


%-------
function plot_RMSIsosurfaces_axisequal

RMSIsosurfacesFig = RMSIsosurfacesHandle;
controls = get(RMSIsosurfacesFig,'userdata');
axes(controls.axes);
axis equal;
set(controls.mPlotNormal,'checked','off');
set(controls.mPlotEqual,'checked','on');

%-------
function plot_RMSIsosurfaces_axisnormal

RMSIsosurfacesFig = RMSIsosurfacesHandle;
controls = get(RMSIsosurfacesFig,'userdata');
axes(controls.axes);
axis normal;
set(controls.mPlotNormal,'checked','on');
set(controls.mPlotEqual,'checked','off');

%-------
function plot_RMSIsosurfaces_addisosurface

RMSIsosurfacesFig = RMSIsosurfacesHandle;
controls = get(RMSIsosurfacesFig,'userdata');
axes(controls.axes);

colors = {'yellow' 'magenta' 'cyan' 'red' 'green' 'blue' 'white' 'black'};

box = dialog('position',[300 300 200 200],'tag','isodialog');
uicontrol('parent',box,'position',[20 180 150 20],'style','text','string','Create Isosurface:',...
   'fontweight','bold');
uicontrol('parent',box,'position',[20 160 120 20],'style','text','string','RMS Iso-Value:',...
   'horizontalalignment','left');
control.RMSval = 1;
control.RMSvalue = uicontrol('parent',box,'position',[105 160 40 20],'string',num2str(control.RMSval),...
   'style','edit','callback','scarpdater_gui boxedit');
control.color = uicontrol('parent',box,'position',[105 130 90 20],'style','popupmenu','string',...
   colors);
uicontrol('parent',box,'position',[20 130 40 20],'string','Color:','style','text','horizontalalignment',...
   'right');

control.cancel = uicontrol('parent',box,'position',[20 50 40 20],'style','pushbutton','string',...
   'Cancel','callback','scarpdater_gui boxcancel');
control.OK = uicontrol('parent',box,'position',[140 50 30 20],'style','pushbutton','string',...
   'OK','callback','scarpdater_gui boxOK');

set(box,'userdata',control);

%-------
function boxcancel

box = findobj(allchild(0),'tag','isodialog');
delete(box);

%-------
function boxedit

box = findobj(allchild(0),'tag','isodialog');

control = get(box,'userdata');
RMSval = str2num(get(control.RMSvalue,'string'));
if(~isempty(RMSval))
   if(RMSval > 0)
      control.RMSval = RMSval;
   end
end

set(control.RMSvalue,'string',num2str(control.RMSval));
set(box,'userdata',control);

%-------
function boxOK

box = findobj(allchild(0),'tag','isodialog');

control = get(box,'userdata');
RMSval = control.RMSval;

colors = {'yellow' 'magenta' 'cyan' 'red' 'green' 'blue' 'white' 'black'};

color = colors{get(control.color,'value')};

mainfig = FigHandle;
parameters = get(mainfig,'userdata');
RMS = parameters.analysis.singleevent.RMS;
ktvec = parameters.analysis.singleevent.ktvec;
bvec = parameters.analysis.singleevent.bvec;
offsetvec = parameters.analysis.singleevent.offsetvec;

delete(box);

IsoFig = RMSIsosurfacesHandle;
cont = get(IsoFig,'userdata');
axes(cont.axes);
scarpdater_createisosurface(ktvec,bvec,offsetvec,RMS,RMSval,color,'transpose');

%-------
function plot_sensitivityanalysis

turnmainmenusoff;

RMSSensitivityAnalysisFig = figure('CloseRequestFcn','scarpdater_gui plot_sensitivityanalysis_quit','position',...
   [200 50 600 600],'Resize','on','Visible','on', ...
   'NumberTitle','off','Name','Single Event Sensitivity Analysis','Units','pixels',...
   'Tag','RMSSensitivityAnalysis_Figure');

mainfig = FigHandle;
parameters = get(mainfig,'Userdata');

bestkt = parameters.analysis.singleevent.bestkt;
bestb = parameters.analysis.singleevent.bestb;
bestoffset = parameters.analysis.singleevent.bestoffset;

minb = bestb - (0.25*bestb);
maxb = bestb + (0.25*bestb);

if(bestb == 0)
   minb = -1;
   maxb = 1;
end

minkt = bestkt - (0.25*bestkt);
minkt = (minkt > 0)*minkt;
maxkt = bestkt + (0.25*bestkt);

if(bestkt == 0)
   minkt = 0;
   maxkt = 1;
end

minoffset = bestoffset - (0.25*bestoffset);
maxoffset = bestoffset + (0.25*bestoffset);

if(bestoffset == 0)
   minoffset = -1;
   maxoffset = 1;
end

x = parameters.data.x;
z = parameters.data.z;
theta = parameters.analysis.singleevent.theta;
a = parameters.analysis.singleevent.a;

scarpdater_plotfs(x,z,theta,a,bestkt,bestb,bestoffset,minkt,minb,...
   minoffset,maxkt,maxb,maxoffset,'none');

subplot(3,1,1)
xlabel('kt');
subplot(3,1,2)
xlabel('b')
ylabel('Error');
subplot(3,1,3)
xlabel('Offset');

%-------
function plot_sensitivityanalysis_quit

SAFig = findobj(allchild(0),'tag','RMSSensitivityAnalysis_Figure');
delete(SAFig);
turnmainmenuson;

%-------
function refreshRMSContourFig

RMSContourFig = RMSContoursHandle;

controls = get(RMSContourFig,'userdata');

contourmin = controls.min;
contourinc = controls.inc;
contourmax = controls.max;

contourvec = contourmin:contourinc:contourmax;

fixeddim = get(controls.fixeddim,'value');
fixedval = get(controls.fixedval,'value');

axes(controls.axes);

mainfig = FigHandle;
parameters = get(mainfig,'userdata');
ktvec = parameters.analysis.singleevent.ktvec;
bvec = parameters.analysis.singleevent.bvec;
offsetvec = parameters.analysis.singleevent.offsetvec;
RMS = parameters.analysis.singleevent.RMS;

scarpdater_contour3dmatrix(ktvec,bvec,offsetvec,RMS,fixeddim,fixedval,contourvec);

switch fixeddim
  case 1
     xlabel('b');
     ylabel('offset');
  case 2
     xlabel('kt');
     ylabel('offset');
  case 3
     xlabel('kt');
     ylabel('b');
end
  


%-------
function turnmainmenusoff

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
set(parameters.menus.mFile,'enable','off');
set(parameters.menus.mEdit,'enable','off');
set(parameters.menus.mCalculate,'enable','off');
set(parameters.menus.mPlot,'enable','off');
set(mainfig,'UserData',parameters);


%-------
function turnmainmenuson

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
set(parameters.menus.mFile,'enable','on');
set(parameters.menus.mEdit,'enable','on');
set(parameters.menus.mCalculate,'enable','on');
set(parameters.menus.mPlot,'enable','on');
set(mainfig,'UserData',parameters);

%---------
function activateRMSplotmenus

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
set(parameters.menus.plotforwardmodels,'enable','on');
set(parameters.menus.plotRMSContours,'enable','on');
set(parameters.menus.plotRMSIsosurfaces,'enable','on');
set(parameters.menus.plotSensitivityAnalysis,'enable','on');











%-----------
% Ramon's callbacks
%-----------

function plot_forwardmodels

  %Main figure control
  mainfig = figure('NumberTitle','off','Name','Diffusion profiles', 'Position',[50 -30 725 750],'Tag','ModelFig');
    uicontrol('Style', 'text', 'Position',[200 710 320 30],  'String',...
       'Profile Diffusion Modeling', 'FontWeight','bold','FontSize',12,'BackgroundColor',[0.8 0.8 0.8]);
    parameters.plot_axes_handle=axes('Units','pixels','Position',[50 100 600 450], 'Visible','On');
    
    
    uicontrol('Style', 'text', 'Position',[50 710 100 35],  'String',...
       'Single event','FontWeight','bold','FontAngle','italic','FontSize',8,...
    'BackgroundColor',[0.8 0.8 0.8]);



  %set defaults
parameters.editboxes.a = 1;
parameters.editboxes.b = 5;
parameters.editboxes.theta = 35;
parameters.editboxes.kt = 1;
parameters.editboxes.xmin = -10;
parameters.editboxes.xmax = 10;
parameters.editboxes.dx = 0.1;
set(mainfig,'UserData',parameters);


%Editable boxes for variable definition

%overall position control:
bottom_del=160;
left_del=0;
align_one=200;
align_two=520;

 uicontrol('Style', 'text', 'Position',[align_one+left_del-40 522+bottom_del 200 20],  'String',...
     'Variable definitions', 'FontWeight','bold','BackgroundColor',[0.8 0.8 0.8]);

%a
  uicontrol('Style', 'text', 'Position',[align_one-110+left_del 500+bottom_del 110 20],  'String', 'half-offset (m); a =',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.a_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',[align_one+left_del 500+bottom_del 40 20],...
     'String',num2str(parameters.editboxes.a),...
     'Callback', 'scarpdater_gui EditBoxReturn_a',...
     'FontSize',8,'BackgroundColor',[1 1 1]);
  %b
   uicontrol('Style', 'text', 'Position',[align_one-150+left_del 475+bottom_del 150 20],  'String', 'fan slope (degrees); b =',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.b_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',[align_one+left_del 475+bottom_del 40 20],...
     'String',num2str(parameters.editboxes.b),...
     'Callback', 'scarpdater_gui EditBoxReturn_b',...
     'FontSize',8,'BackgroundColor',[1 1 1]);
  %theta
  uicontrol('Style', 'text', 'Position',[align_one-185+left_del 450+bottom_del 180 20],  'String',...
     'scarp slope (degrees);  theta  =',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.theta_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',[align_one+left_del 450+bottom_del 40 20],...
     'String',num2str(parameters.editboxes.theta),...
     'Callback', 'scarpdater_gui EditBoxReturn_theta',...
     'FontSize',8,'BackgroundColor',[1 1 1]);
  %kt
  uicontrol('Style', 'text', 'Position',[align_one-83+left_del 425+bottom_del 80 20],  'String', 'kt (m^2); kt =',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.kt_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',[align_one+left_del 425+bottom_del 40 20],...
     'String',num2str(parameters.editboxes.kt),...
     'Callback', 'scarpdater_gui EditBoxReturn_kt',...
     'FontSize',8,'BackgroundColor',[1 1 1]);
  %xmin
  pos=225;
  text_bottom=475;
  box_bottom=500;
   uicontrol('Style', 'text', 'Position',[align_one-155+left_del+pos text_bottom+bottom_del 50 20],  'String', 'xmin (m)',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.xmin_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',...
     [align_one-150+left_del+pos box_bottom+bottom_del 40 20],...
     'String',num2str(parameters.editboxes.xmin),...
     'Callback', 'scarpdater_gui EditBoxReturn_xmin',...
     'FontSize',8,'BackgroundColor',[1 1 1]);
  %dx
  uicontrol('Style', 'text', 'Position',[align_one-100+left_del+pos text_bottom+bottom_del 50 20],  'String', 'dx (m)',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.dx_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',...
     [align_one-95+left_del+pos box_bottom+bottom_del 50 20],...
     'String',num2str(parameters.editboxes.dx),...
     'Callback', 'scarpdater_gui EditBoxReturn_dx',...
     'FontSize',8,'BackgroundColor',[1 1 1]); 
  %xmax
  uicontrol('Style', 'text', 'Position',[align_one-50+left_del+pos text_bottom+bottom_del 55 20],  'String', 'xmax (m)',...
     'FontSize',8,'BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.xmax_edit = uicontrol('parent',mainfig,'Style', 'edit', 'Position',[align_one-45+left_del+pos box_bottom+bottom_del 40 20],...
     'String',num2str(parameters.editboxes.xmax),...
     'Callback', 'scarpdater_gui EditBoxReturn_xmax',...
     'FontSize',8,'BackgroundColor',[1 1 1]);
  
  %restore defaults
	uicontrol('Style', 'pushbutton', 'String', 'Restore defaults',...
        'Position', [align_one+100 435+bottom_del  105 25], 'Callback', 'scarpdater_gui defaults', 'BackgroundColor',[0.8 0.8 0.8]);

  
  %Plotting control
  uicontrol('Style', 'text', 'Position',[align_two+left_del-10 470+bottom_del 120 35],  'String',...
     'Axis scaling and figure overlay', 'FontWeight','bold','BackgroundColor',[0.8 0.8 0.8]);
  parameters.editboxes.hpop = uicontrol('Style', 'popup', 'String', 'hold on|hold off',...
           'Position', [align_two+left_del 395+bottom_del 100 50],...
           'Callback', 'scarpdater_gui holdcontrol');
  parameters.editboxes.axispop = uicontrol('Style', 'popup', 'String', 'axis equal|axis normal',...
           'Position', [align_two+left_del 420+bottom_del 100 50],...
           'Callback', 'scarpdater_gui axiscontrol');
        
 uicontrol('Style', 'text', 'Position',[align_two+left_del-45 522+bottom_del 200 20],  'String',...
     'Show data', 'FontWeight','bold','BackgroundColor',[0.8 0.8 0.8]);
 parameters.editboxes.datacheck = uicontrol('Style', 'checkbox', ...
       'Position', [align_two+left_del+50 515+bottom_del 10 10],...
       'BackgroundColor',[0.8 0.8 0.8],...
       'Callback', 'scarpdater_gui plotdata');
    
    
    
      
%here comes the data

fig = FigHandle;
mainparameters = get(fig,'userdata');


parameters.Xobserved=mainparameters.data.x;
parameters.Hobserved=mainparameters.data.z;
parameters.dataplot_handle = plot(parameters.Xobserved,parameters.Hobserved, 'r.');
hold on
set(parameters.dataplot_handle,'Visible','Off')
set(mainfig,'UserData',parameters);

finitescarp

%legend('Observed','Initial','Model',-1)



%-----
function myfig = ModelFigHandle
myfig = findobj(allchild(0),'Tag','ModelFig');

function defaults
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
parameters.editboxes.a = 1;
set(parameters.editboxes.a_edit,'String',num2str(parameters.editboxes.a));
parameters.editboxes.b = 5;
set(parameters.editboxes.b_edit,'String',num2str(parameters.editboxes.b));
parameters.editboxes.theta = 35;
set(parameters.editboxes.theta_edit,'String',num2str(parameters.editboxes.theta));
parameters.editboxes.kt = 1;
set(parameters.editboxes.kt_edit,'String',num2str(parameters.editboxes.kt));
parameters.editboxes.xmin = -10;
set(parameters.editboxes.xmin_edit,'String',num2str(parameters.editboxes.xmin));
parameters.editboxes.xmax = 10;
set(parameters.editboxes.xmax_edit,'String',num2str(parameters.editboxes.xmax));
parameters.editboxes.dx = 0.1;
set(parameters.editboxes.dx_edit,'String',num2str(parameters.editboxes.dx));
cla
parameters.dataplot_handle = plot(parameters.Xobserved,parameters.Hobserved, 'r.');
hold on
set(parameters.dataplot_handle,'Visible','Off');
set(parameters.editboxes.datacheck,'Value',0);
set(mainfig,'UserData',parameters);
finitescarp
%legend('Observed','Initial','Model',-1)


%-----Edit box functions
function EditBoxReturn_a
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.a_edit,'String'),'%f');
if(~isempty(newvalue) )
   parameters.editboxes.a = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.a_edit,'String',num2str(parameters.editboxes.a));
finitescarp

function EditBoxReturn_b
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.b_edit,'String'),'%f');
if(~isempty(newvalue) )
   parameters.editboxes.b = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.b_edit,'String',num2str(parameters.editboxes.b));
finitescarp

function EditBoxReturn_theta
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.theta_edit,'String'),'%f');
if(~isempty(newvalue) )
   parameters.editboxes.theta = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.theta_edit,'String',num2str(parameters.editboxes.theta));
finitescarp

function EditBoxReturn_kt
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.kt_edit,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0))
   parameters.editboxes.kt = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.kt_edit,'String',num2str(parameters.editboxes.kt));
finitescarp

function EditBoxReturn_xmin
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.xmin_edit,'String'),'%f');
if(~isempty(newvalue) )
   parameters.editboxes.xmin = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.xmin_edit,'String',num2str(parameters.editboxes.xmin));
finitescarp

function EditBoxReturn_dx
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.dx_edit,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0))
   parameters.editboxes.dx = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.dx_edit,'String',num2str(parameters.editboxes.dx));
finitescarp

function EditBoxReturn_xmax
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.editboxes.xmax_edit,'String'),'%f');
if(~isempty(newvalue) )
   parameters.editboxes.xmax = newvalue;
   set(mainfig,'UserData',parameters);
end
set(parameters.editboxes.xmax_edit,'String',num2str(parameters.editboxes.xmax));
finitescarp






%------Scarp functions
function finitescarp
%This function solves the finitescarp initial conditions problem for
%thetadegrees is the initial scarp slope in degrees
%theta is the initial scarp slope in radians
%a = half scarp initial height
%x = distance along profile
%t = time
%k = diffusivity in distance^2/time
%kt = morphologic age (k*t) distance^2
%bdegrees is far field slope in degrees
%b = far field slope in radians
%from Hanks, T. C. and D. J. Andrews, Effect of far-field slope on morphologic dating 
%of scarplike landforms, Journal of Geophysical Research, 94, 565-573, 1989.

mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
x=(parameters.editboxes.xmin:parameters.editboxes.dx:parameters.editboxes.xmax);
parameters.x=x;
a = parameters.editboxes.a;
b=rads(parameters.editboxes.b);
theta=rads(parameters.editboxes.theta);
kt=parameters.editboxes.kt;
if theta>=rads(75)
   parameters.H=(a.*erf(x./(2.*sqrt(kt)))+b.*x).*-1;%Note -1 for flip!
else
fkt=4.*kt;
sfkt=sqrt(fkt);
ang=theta-b;
A=a./ang;
X=x+A;
Xm=x-A;
parameters.H=(ang.*sqrt(kt/pi).*(exp(-((X.^2)./fkt))-exp(-((Xm.^2)./fkt)))+(ang/2).*(X.*erf(X./sfkt)-Xm .*erf(Xm./sfkt))+b.*x).*-1;%Note -1 for flip!

end
set(mainfig,'UserData',parameters);
plotfinitescarp

%-------Plot functions
function plotfinitescarp
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
%subplot(2,1,2)
axes(parameters.plot_axes_handle)
x=(parameters.editboxes.xmin:parameters.editboxes.dx:parameters.editboxes.xmax);
parameters.x=x;
a = parameters.editboxes.a;
b=rads(parameters.editboxes.b);
theta=rads(parameters.editboxes.theta);
kt=0.0001;
if theta>=rads(75)
   Hinitial=(a.*erf(x./(2.*sqrt(kt)))+b.*x).*-1;%Note -1 for flip!

else
fkt=4.*kt;
sfkt=sqrt(fkt);
ang=theta-b;
A=a./ang;
X=x+A;
Xm=x-A;
Hinitial=(ang.*sqrt(kt/pi).*(exp(-((X.^2)./fkt))-exp(-((Xm.^2)./fkt)))+(ang/2).*(X.*erf(X./sfkt)-Xm .*erf(Xm./sfkt))+b.*x).*-1;%Note -1 for flip!

end
plot(x,Hinitial,'b--')
hold on
plot(x,parameters.H,'k-')
xlabel('Distance along profile (m)')
ylabel('Elevation (m)')
grid on;
holdcontrol
axiscontrol


function holdcontrol
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
val = get(parameters.editboxes.hpop,'Value');
    if val == 1
        hold on
    elseif val == 2
       hold off
       set(parameters.editboxes.datacheck,'Value',0)
end
    
function axiscontrol
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
val = get(parameters.editboxes.axispop,'Value');
    if val == 1
        axis equal
    elseif val == 2
       axis normal
    end


function plotdata
mainfig = ModelFigHandle;
parameters = get(mainfig,'UserData');
dataval = get(parameters.editboxes.datacheck,'Value');
holdval = get(parameters.editboxes.hpop,'Value');

if holdval == 1
   if dataval == 1
      set(parameters.dataplot_handle,'Visible','On')
  elseif dataval == 0
      set(parameters.dataplot_handle,'Visible','Off')
   end
elseif holdval == 2
   if dataval == 1
      parameters.dataplot_handle= plot(parameters.Xobserved,parameters.Hobserved,'r.');
      set(parameters.dataplot_handle,'Visible','On')
   elseif dataval == 0
      parameters.dataplot_handle= plot(parameters.Xobserved,parameters.Hobserved,'r.');
      set(parameters.dataplot_handle,'Visible','Off')
   end
end
axiscontrol




%-------Utility functions
function r = rads(degrees)
r = degrees * (pi/180);

function d = deg(rads)
d = rads*(180/pi)
