function penckgui(functioncall)

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

  case 'new'
    answer = questdlg('Really clear all Penck1D variables?','','Yes','No','No');
    if(strcmp(answer,'Yes'))
      mainfig = FigHandle;
      delete(gcbf)
      clear
      penckgui
    end

  case 'open'
    variableload;

  case 'save'
    variablesave;

  case 'changedx'
    changedx;

  case 'changenx'
    changenx;

  case 'changeXo'
    changexo;

  case 'changedt'
    changedt;

  case 'stabledt'
    stabledt;

  case 'changet'
    changet;

  case 'lbctypechange'
    lbctypechange;

  case 'rbctypechange'
    rbctypechange;

  case 'changelbc'
    changelbc;

  case 'changerbc'
    changerbc;

  case 'changefaulttype'
    changefaulttype;

  case 'changefxo'
    changefxo;

  case 'changefzo'
    changefzo;

  case 'changeL'
    changeL;

  case 'changesr'
    changesr;

  case 'changebeta'
    changebeta;

  case 'changekappa'
    changekappa;

  case 'changeBa'
    changeBa;

  case 'changeBb'
    changeBb;

  case 'importtopo'
    importtopo;

  case 'importbr'
    importbr;

  case 'import'
    importtopobr;

  case 'exportparams'
    exportparams;

  case 'exportseltopo'
    exportseltopo;

  case 'exportselbr'
    exportselbr;

  case 'exportsel'
    exportsel;

  case 'switchimportdata'
    switchimportdata;

  case 'interpolateprofileimport'
    interpolateprofileimport;

  case 'interpolatebedrockimport'
    interpolatebedrockimport;

  case 'flattopo'
    flattopo;

  case 'slopetopo'
    slopetopo;

  case 'gridproftoprofile'
    gridproftoprofile;

  case 'gridbrtobr'
    gridbrtobr;

  case 'profiletoinitialprofile'
    profiletoinitialprofile;

  case 'bedrocktoinitialbedrock'
    bedrocktoinitialbedrock;

  case 'profiletoinitialbedrock'
    profiletoinitialbedrock;

  case 'bedrocktoinitialprofile'
    bedrocktoinitialprofile;

  case 'offsetprofile'
    offsetprofile;

  case 'offsetbedrock'
    offsetbedrock;

  case 'profiletobedrock'
    profiletobedrock;

  case 'plotinitialconditions'
    plotinitialconditions;

  case 'plotfaultdisplacements'
    plotfaultdisplacements;

  case 'plotfaultgeometry'
    plotfaultgeometry;

  case 'plotmodelresults'
    plotmodelresults;

  case 'runtlmodel'
    runtlmodel;

  case 'runplmodel'
    runplmodel;

  case 'changeresultfigt'
    changeresultfigt;

  case 'noexag'
    noexag;

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

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

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

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

%-----------------------------
function fig = ResultsFigHandle

fig = findobj(allchild(0),'Tag','ResultsPlot');

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

mainfig = figure('Position',[300 100 800 800],'CloseRequestFcn', ...
   'penckgui quit','Resize','off','menubar','none','Visible','off', ...
   'NumberTitle','off','Name','Penck 1D Fault Scarp Simulation Program', ...
   'Color',[1 1 1],'Colormap',gray(256),'Tag','MainFigure');

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');
mInitialConditions = uimenu('parent',mainfig,'label','&Initial Conditions');
mPlot = uimenu('parent',mainfig,'label','&Plot');
mRun = uimenu('parent',mainfig,'label','&Run');

% File menu:

uimenu('parent',mFile,'label','&New','Callback','penckgui new');
uimenu('parent',mFile,'label','&Open...','Callback','penckgui open');
uimenu('parent',mFile,'label','&Save As...','Callback','penckgui save');
msubImport = uimenu('parent',mFile,'label','&Import');
msubExport = uimenu('parent',mFile,'label','&Export');
uimenu('parent',mFile,'label','&Quit','Callback','penckgui quit', ...
   'separator','on');

% Import submenu:

uimenu('parent',msubImport,'label','&Import X-Z data...','Callback', ...
   'penckgui importtopo');
uimenu('parent',msubImport,'label','&Import X-B data...','Callback', ...
   'penckgui importbr');
uimenu('parent',msubImport,'label','&Import X-Z-B data...','Callback', ... 
   'penckgui import');

% Export submenu:
uimenu('parent',msubExport,'label','&Export Model Parameters...', ...
   'callback','penckgui exportparams');
uimenu('parent',msubExport,'label','&Export X-Z data...', ...
   'Callback', 'penckgui exportseltopo');
uimenu('parent',msubExport,'label','&Export X-B data...', ...
   'Callback', 'penckgui exportselbr');
uimenu('parent',msubExport,'label','&Export X-Z-B data...', ...
   'Callback', 'penckgui exportsel');

% Edit menu:

uimenu('parent',mEdit,'label', ...
   'Switch Import Data (bedrock->profile, profile->bedrock)', ...
   'Callback','penckgui switchimportdata')
msubGrid = uimenu('parent',mEdit,'label','Sort and Grid Import Data');

% Sort and Grid Import Data submenu:
uimenu('parent',msubGrid,'label','Profile Import Data','callback', ...
   'penckgui interpolateprofileimport');
uimenu('parent',msubGrid,'label','Bedrock Import Data','callback', ...
   'penckgui interpolatebedrockimport');

% Initial conditions menu:
uimenu('parent',mInitialConditions,'label', ...
   'Flat Initial Topography at z = 0','callback','penckgui flattopo');
uimenu('parent',mInitialConditions,'label', ...
   'Sloping initial profile...','callback','penckgui slopetopo');
uimenu('parent',mInitialConditions,'label', ...
   'Apply Gridded Profile Data to Initial Condition (Topography)', ...
   'callback','penckgui gridproftoprofile','separator','on');
uimenu('parent',mInitialConditions,'label', ...
   'Apply Gridded Bedrock Data to Initial Condition (Bedrock)', ...
   'callback','penckgui gridbrtobr');
uimenu('parent',mInitialConditions,'label', ...
   'Current Profile Elevation --> Initial Condition (Topography)', ...
   'Callback','penckgui profiletoinitialprofile','separator','on');
uimenu('parent',mInitialConditions,'label', ...
   'Current Bedrock Elevation --> Initial Condition (Bedrock)', ...
   'Callback','penckgui bedrocktoinitialbedrock');
uimenu('parent',mInitialConditions,'label', ...
   'Current Profile Elevation --> Initial Condition (Bedrock)', ...
   'Callback','penckgui profiletoinitialbedrock');
uimenu('parent',mInitialConditions,'label', ...
   'Current Bedrock Elevation --> Initial Condition (Topography)', ...
   'Callback','penckgui bedrocktoinitialprofile');
uimenu('parent',mInitialConditions,'label','Offset Profile...', ...
   'callback','penckgui offsetprofile','separator','on');
uimenu('parent',mInitialConditions,'label','Offset Bedrock...', ...
   'callback','penckgui offsetbedrock');
uimenu('parent',mInitialConditions,'label','Copy Profile to Bedrock', ...
   'callback','penckgui profiletobedrock','separator','on');

% Plot menu:
uimenu('parent',mPlot,'label','Initial Conditions...','callback', ...
   'penckgui plotinitialconditions');
uimenu('parent',mPlot,'label','Fault Displacements...','callback', ...
   'penckgui plotfaultdisplacements');
uimenu('parent',mPlot,'label','Fault Geometry and Initial Conditions...', ...
   'callback','penckgui plotfaultgeometry');
uimenu('parent',mPlot,'label','Model Results...','callback', ...
   'penckgui plotmodelresults');


% Run menu:
uimenu('parent',mRun,'label','Run Transport Limited Model','Callback', ...
   'penckgui runtlmodel');
uimenu('parent',mRun,'label','Run Production Limited Model','Callback', ...
   'penckgui runplmodel');

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

white = [1 1 1];
title=uicontrol('Parent',mainfig,'Style','text','String', ...
   'Penck 1D ','Position',[250 700 300 80],'BackgroundColor', ...
   [1 1 1],'FontSize',36,'FontAngle','italic','FontWeight','bold');
subtitle=uicontrol('Parent',mainfig,'Style','text','String', ...
   'Transport- and production-limited fault scarp simulation software', ...
   'BackgroundColor',white,'FontSize',12,'Position',[100 642 600 80], ...
   'FontAngle','italic','FontWeight','bold');
authors=uicontrol('Parent',mainfig,'Style','text','String', ...
   'model developed and written by George Hilley and J Ramon Arrowsmith', ...
   'Position',[100 605 600 80],'BackgroundColor', [1 1 1],'FontSize',12);
ASU=uicontrol('Parent',mainfig,'Style','text','String', ...
   'Arizona State University','Position',[100 587 600 80], ...
   'BackgroundColor',[1 1 1],'FontSize',12,'FontAngle','italic');
copyright=uicontrol('Parent',mainfig,'Style','text','String', ...
   '(C) 1997-2001','Position',[100 568 600 80],'BackgroundColor', ...
   white,'FontSize',12,'FontAngle','italic');
fund=uicontrol('Parent',mainfig,'Style','text','String', ...
  'Finite Difference Parameters:','Position',[0 300 300 20],'FontSize',12, ...
  'FontWeight','bold','BackgroundColor',white);

parameters = get(mainfig,'UserData');
% Finite difference parameter controls:

uicontrol('Parent',mainfig,'Style','text','string','dx = ','Position', ...
  [60 285 40 20],'FontSize',12,'FontAngle','italic','BackgroundColor',white);
uicontrol('Parent',mainfig,'Style','text','string','nx = ','Position', ...
  [60 265 40 20],'FontSize',12,'FontAngle','italic','BackgroundColor',white);
uicontrol('Parent',mainfig,'Style','text','string','Xo = ','Position', ...
  [160 285 40 20],'FontSize',12,'FontAngle','italic','BackgroundColor',white);
uicontrol('Parent',mainfig,'Style','text','string','dt = ','Position', ...
  [160 265 40 20],'FontSize',12,'FontAngle','italic','BackgroundColor',white);
parameters.dxeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'Position',[100 283 40 20], 'String',num2str(parameters.dx),'callback', ...
  'penckgui changedx', 'FontSize',9,'BackgroundColor',white);
parameters.nxeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'Position',[100 263 40 20], 'String',num2str(parameters.nx),'callback', ...
  'penckgui changenx', 'FontSize',9,'BackgroundColor',white);
parameters.xoeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'Position',[200 283 40 20], 'String',num2str(parameters.Xo),'callback', ...
  'penckgui changeXo', 'FontSize',9,'BackgroundColor',white);
parameters.dteditbox = uicontrol('parent',mainfig,'style','edit', ...
  'Position',[200 263 40 20], 'String',num2str(parameters.dt),'callback', ...
  'penckgui changedt', 'FontSize',9,'BackgroundColor',white);
parameters.dtpushbutton = uicontrol('parent',mainfig,'style','pushbutton', ...
  'Position',[250 263 120 20], 'String','Maximum stable t-step', ...
  'callback', 'penckgui stabledt', 'FontSize',9,'BackgroundColor',white);
uicontrol('Parent',mainfig,'Style','text','string','t (output) = ', ...
  'Position', [60 245 90 20],'FontSize',12,'FontAngle','italic', ...
  'BackgroundColor',white,'HorizontalAlignment','left');
parameters.timeeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'Position',[140 243 200 20], 'String', ...
  make_commadelimitedarray(parameters.t),'callback', 'penckgui changet', ...
 'FontSize',9,'BackgroundColor',white);


% Geomorphic Boundary Condition Controls:

uicontrol('Parent',mainfig,'Style','text','String', ...
  'Geomorphic Boundary Conditions:','Position',[20 200 300 20],'FontSize', ...
  12, 'FontWeight','bold','BackgroundColor',white);
uicontrol('Parent',mainfig,'Style','text','String', ...
  'Left Side (Least X) Boundary Conditions:','Position',[50 170 300 20], ...
  'FontSize', 10,'BackgroundColor',white,'HorizontalAlignment','left');
uicontrol('Parent',mainfig,'Style','text','String', ...
  'Right Side (Greatest X) Boundary Conditions:','Position', ...
  [50 90 300 20],'FontSize', 10,'BackgroundColor',white, ...
  'HorizontalAlignment','left');
parameters.lbctypepopup = uicontrol('Parent',mainfig,'style','popupmenu', ...
  'String', {'Constant Elevation BC...','Constant Flux BC...'},'FontSize', ...
  12,'callback','penckgui lbctypechange','Position',[50 150 250 20], ...
  'BackgroundColor',white);
parameters.rbctypepopup = uicontrol('Parent',mainfig,'style','popupmenu', ...
  'String', {'Constant Elevation BC...','Constant Flux BC...'},'FontSize', ...
  12,'callback','penckgui rbctypechange','Position',[50 70 250 20], ...
  'BackgroundColor',white);
parameters.lbceditbox = uicontrol('Parent',mainfig,'style','edit', ...
  'String',num2str(parameters.lbc),'callback','penckgui changelbc', ...
  'Position', [150 130 50 20], 'BackgroundColor',white);
parameters.rbceditbox = uicontrol('Parent',mainfig,'style','edit', ...
  'String',num2str(parameters.rbc),'callback','penckgui changerbc', ...
  'Position', [150 50 50 20], 'BackgroundColor',white);

% Model Parameters (Rates and Geometries):
uicontrol('Parent',mainfig,'Style','text','String', ...
  'Model Parameters:','Position',[400 300 300 20],'FontSize', ...
  12, 'FontWeight','bold','BackgroundColor',white,'HorizontalAlignment', ...
  'left');
uicontrol('Parent',mainfig,'Style','text','String', ...
  'Tectonic Rates and Geometries:','Position',[410 280 300 20],'FontSize', ...
  12, 'FontWeight','bold','BackgroundColor',white,'HorizontalAlignment', ...
  'left');
uicontrol('Parent',mainfig,'Style','text','String','Fault Type:', ...
  'Position',[425 260 150 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.typepopup = uicontrol('parent',mainfig,'style','popupmenu', ...
  'string',{'Normal Fault' 'Reverse Fault'},'FontSize',12,'callback', ...
  'penckgui changefaulttype','Position',[500 263 150 20],'BackgroundColor', ...
  white);
uicontrol('parent',mainfig,'style','text','string','Fault Tip Location: ', ...
  'Position',[425 230 120 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
uicontrol('parent',mainfig,'style','text','string','Fxo = ', ...
  'Position',[545 230 40 20],'BackgroundColor',white,'FontSize',10, ...
  'HorizontalAlignment','left');
parameters.Fxoeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.Fxo),'Position',[590 232 60 20], ...
  'BackgroundColor',white,'FontSize',10,'Callback','penckgui changefxo');
uicontrol('parent',mainfig,'style','text','string','Fzo = ', ...
  'Position',[545 210 40 20],'BackgroundColor',white,'FontSize',10, ...
  'HorizontalAlignment','left');
parameters.Fzoeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.Fzo),'Position',[590 212 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changefzo');
uicontrol('parent',mainfig,'style','text','string','Fault Length: ', ...
  'Position',[425 185 100 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.Leditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.L),'Position',[590 187 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changeL');
uicontrol('parent',mainfig,'style','text','string','Fault Slip Rate: ', ...
  'Position',[425 160 100 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.sreditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.sr),'Position',[590 162 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changesr');
uicontrol('parent',mainfig,'style','text','string','Fault Dip (degrees): ', ...
  'Position',[425 135 150 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.betaeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.beta),'Position',[590 137 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changebeta');

uicontrol('Parent',mainfig,'Style','text','String', ...
  'Geomorphic Rates:','Position',[410 110 300 20],'FontSize', ...
  12, 'FontWeight','bold','BackgroundColor',white,'HorizontalAlignment', ...
  'left');
uicontrol('parent',mainfig,'style','text','string','Kappa: ', ...
  'Position',[425 90 100 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.kappaeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.kappa),'Position',[590 92 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changekappa');
uicontrol('parent',mainfig,'style','text','string','Ba: ', ...
  'Position',[425 65 60 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.Baeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.Ba),'Position',[590 67 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changeBa');
uicontrol('parent',mainfig,'style','text','string','Bb: ', ...
  'Position',[425 40 60 20],'BackgroundColor',white,'FontSize',10, ...
  'FontWeight','bold','HorizontalAlignment','left');
parameters.Bbeditbox = uicontrol('parent',mainfig,'style','edit', ...
  'string',num2str(parameters.Bb),'Position',[590 42 60 20], ...
  'BackgroundColor',white,'FontSize',10,'callback','penckgui changeBb');

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

load titlepict
mainfig.img_axes = axes('Parent',mainfig,...
             'YDir','reverse',...
             'XLim',[0.5 700.5],...
             'YLim',[0.5 220.5],...
             'CLim',[0 255],...
             'XTick',[],...
             'YTick',[],...
             'Units','pixels','Position',[50 350 700 220]);
mainfig.img = image('parent',mainfig.img_axes,'CData',title_imagedata, ...
   'CDataMapping','scaled','EraseMode','none');


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

parameters.dx = 1;
parameters.nx = 1001;
parameters.Xo = -500;
parameters.kappa = 0.004;
parameters.Ba = 0.00008;
parameters.Bb = 0.1;
parameters.Fxo = 0;
parameters.Fzo = 0.001;
parameters.sr = 0.001;
parameters.beta = 60;
parameters.faulttype = 'normal';
parameters.L = 5000;
parameters.dt = 0.25.*(parameters.dx.^2)./parameters.kappa;
parameters.lbc = 0;
parameters.rbc = 0;
parameters.lbctype = 0;
parameters.rbctype = 0;
parameters.t = [1 10 100 1000 10000];
parameters.modeluptodate = 0;
parameters.profuptodate = 0;
parameters.bruptodate = 0;
parameters.icprofutd = 0;
parameters.icbrutd = 0;
parameters.x = parameters.Xo:parameters.dx:(parameters.nx-1).* ...
   parameters.dx + parameters.Xo;
parameters.importxprof = [];
parameters.importzprof = [];
parameters.importxbr = [];
parameters.importzbr = [];
parameters.Profile = [];
parameters.Bedrock = [];
parameters.ResultsProfile = [];
parameters.ResultsBedrock = [];
parameters.ProfileInitCond = [];
parameters.BedrockInitCond = [];
parameters.PenckFile = 1;
set(mainfig,'UserData',parameters,'HandleVisibility','callback');

%----------------------
function changedx(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.dxeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0))
    parameters.dx = newvalue;
    if(parameters.dt > (0.25.*(parameters.dx.^2)./parameters.kappa))
      parameters.dt = 0.25.*(parameters.dx.^2)./parameters.kappa;
    end
    parameters.modeluptodate = 0;
    parameters.profuptodate = 0;
    parameters.bruptodate = 0;
    parameters.icprofutd = 0;
    parameters.icbrutd = 0;
    set(mainfig,'UserData',parameters);
end
set(parameters.dxeditbox,'String',num2str(parameters.dx));
set(parameters.dteditbox,'String',num2str(parameters.dt));
recalculatex;

%----------------------
function changenx(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.nxeditbox,'String'),'%d');
if(~isempty(newvalue) & (newvalue > 0))
    parameters.nx = newvalue;
    parameters.modeluptodate = 0;
    parameters.profuptodate = 0;
    parameters.bruptodate = 0;
    parameters.icprofutd = 0;
    parameters.icbrutd = 0;
end
set(parameters.nxeditbox,'String',num2str(parameters.nx));
set(mainfig,'UserData',parameters);
recalculatex;

%----------------------
function changexo(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.xoeditbox,'String'),'%f');
if(~isempty(newvalue))
    parameters.Xo = newvalue;
    parameters.modeluptodate = 0;
    parameters.profuptodate = 0;
    parameters.bruptodate = 0;
    parameters.icprofutd = 0;
    parameters.icbrutd = 0;
end
set(parameters.xoeditbox,'String',num2str(parameters.Xo));
set(mainfig,'UserData',parameters);
recalculatex;

%----------------------
function changedt(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.dteditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0) & (newvalue < ...
   0.25.*(parameters.dx.^2)./parameters.kappa))
  parameters.dt = newvalue;
end
parameters.modeluptodate = 0;
set(parameters.dteditbox,'String',num2str(parameters.dt));
set(mainfig,'UserData',parameters);

%----------------------
function stabledt(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
if(parameters.dt ~= 0.25*(parameters.dx.^2)./parameters.kappa)
  parameters.dt = 0.25*(parameters.dx.^2)./parameters.kappa;
  parameters.modeluptodate = 0;
end
set(parameters.dteditbox,'String',num2str(parameters.dt));
set(mainfig,'UserData',parameters);

%----------------------
function changet(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = get_commadelimitedarray(get(parameters.timeeditbox,'String'));
i = find(newvalue > 0);
newvalue = newvalue(i);
if(~isempty(newvalue))
  parameters.t = newvalue;
  parameters.modeluptodate = 0;
end
set(parameters.timeeditbox,'String',make_commadelimitedarray(parameters.t));
set(mainfig,'UserData',parameters);


%----------------------
function lbctypechange(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
parameters.lbctype = get(parameters.lbctypepopup,'Value') - 1;
parameters.modeluptodate = 0;
set(mainfig,'UserData',parameters);

%----------------------
function rbctypechange(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
parameters.rbctype = get(parameters.rbctypepopup,'Value') - 1;
parameters.modeluptodate = 0;
set(mainfig,'UserData',parameters);

%----------------------
function changelbc(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.lbceditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue ~= parameters.lbc))
  parameters.lbc = newvalue;
  parameters.modeluptodate = 0;
end
set(parameters.lbceditbox,'String',num2str(parameters.lbc));
set(mainfig,'UserData',parameters);

%----------------------
function changerbc(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.rbceditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue ~= parameters.rbc))
  parameters.rbc = newvalue;
  parameters.modeluptodate = 0;
end
set(parameters.rbceditbox,'String',num2str(parameters.rbc));
set(mainfig,'UserData',parameters);

%----------------------
function changefaulttype(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
value = get(parameters.typepopup,'Value');
switch value 
  case 1
    parameters.faulttype = 'normal';
  case 2
    parameters.faulttype = 'reverse';
end
parameters.modeluptodate = 0;
set(mainfig,'UserData',parameters);

%----------------------
function changefxo(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.Fxoeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue ~= parameters.Fxo))
    parameters.Fxo = newvalue;
    parameters.modeluptodate = 0;
end
set(parameters.Fxoeditbox,'String',num2str(parameters.Fxo));
set(mainfig,'UserData',parameters);

%----------------------
function changefzo(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.Fzoeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue >= 0) & (newvalue ~= parameters.Fzo))
    parameters.Fzo = newvalue;
    parameters.modeluptodate = 0;
end
set(parameters.Fzoeditbox,'String',num2str(parameters.Fzo));
set(mainfig,'UserData',parameters);

%----------------------
function changeL(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.Leditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0) & (newvalue ~= parameters.L))
    parameters.L = newvalue;
    parameters.modeluptodate = 0;
end
set(parameters.Leditbox,'String',num2str(parameters.L));
set(mainfig,'UserData',parameters);

%----------------------
function changesr(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.sreditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0) & (newvalue ~= parameters.sr))
    parameters.sr = newvalue;
    parameters.modeluptodate = 0;
end
set(parameters.sreditbox,'String',num2str(parameters.sr));
set(mainfig,'UserData',parameters);

%----------------------
function changebeta(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.betaeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue >= -90) & (newvalue <= 90) & ...
   (newvalue ~= parameters.beta))
    parameters.beta = newvalue;
    parameters.modeluptodate = 0;
end
set(parameters.betaeditbox,'String',num2str(parameters.beta));
set(mainfig,'UserData',parameters);

%----------------------
function changekappa(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.kappaeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0) & (newvalue ~= parameters.kappa))
    parameters.kappa = newvalue;
    parameters.modeluptodate = 0;
end
if(parameters.dt > 0.25*(parameters.dx.^2)./parameters.kappa)
  parameters.dt = 0.25*(parameters.dx.^2)./parameters.kappa;
  set(parameters.dteditbox,'String',num2str(parameters.dt));
end
set(parameters.kappaeditbox,'String',num2str(parameters.kappa));
set(mainfig,'UserData',parameters);

%----------------------
function changeBa(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.Baeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0) & (newvalue ~= parameters.Ba))
    parameters.Ba = newvalue;
    modeluptodate = 0;
end
set(parameters.Baeditbox,'String',num2str(parameters.Ba));
set(mainfig,'UserData',parameters);

%----------------------
function changeBb(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
newvalue = sscanf(get(parameters.Bbeditbox,'String'),'%f');
if(~isempty(newvalue) & (newvalue > 0) & (newvalue ~= parameters.Bb))
    parameters.Bb = newvalue;
    parameters.modeluptodate = 0;
end
set(parameters.Bbeditbox,'String',num2str(parameters.Bb));
set(mainfig,'UserData',parameters);

%----------------------
function variableload(mainfig)
mainfig = FigHandle;
PenckFile = 0;
filename = uigetfile('*.mat','PENCK1D file to open...');
if(filename ~= 0)
  load(filename)
  if(PenckFile == 1)
    parameters = get(mainfig,'UserData');
    parameters.dx = dx;
    parameters.nx = nx;
    parameters.Xo = Xo;
    parameters.kappa = kappa;
    parameters.Ba = Ba;
    parameters.Bb = Bb;
    parameters.Fxo = Fxo;
    parameters.Fzo = Fzo;
    parameters.sr = sr;
    parameters.beta = betavar;
    parameters.faulttype = faulttype;
    parameters.L = L;
    parameters.dt = dt;
    parameters.lbc = lbc;
    parameters.rbc = rbc;
    parameters.lbctype = lbctype;
    parameters.rbctype = rbctype;
    parameters.t = t;
    parameters.modeluptodate = modeluptodate;
    parameters.profuptodate = profuptodate;
    parameters.bruptodate = bruptodate;
    parameters.icprofutd = icprofutd;
    parameters.icbrutd = icbrutd;
    parameters.x = x;
    parameters.importxprof = importxprof;
    parameters.importzprof = importzprof;
    parameters.importxbr = importxbr;
    parameters.importzbr = importzbr;
    parameters.Profile = Profile;
    parameters.Bedrock = Bedrock;
    parameters.ResultsProfile = ResultsProfile;
    parameters.ResultsBedrock = ResultsBedrock;
    parameters.ProfileInitCond = ProfileInitCond;
    parameters.BedrockInitCond = BedrockInitCond;
    parameters.PenckFile = PenckFile;

    set(mainfig,'UserData',parameters);
    refreshfigure(mainfig);

  else
    errordlg(strcat(filename,' is not a valid PENCK1D input file.'), ...
      'Open Error');
  end
end

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

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

if(parameters.modeluptodate == 0)
  parameters.ResultsProfile = [];
end

if(parameters.modeluptodate == 0)
  parameters.ResultsBedrock = [];
end

if(filename ~= 0)
  dx = parameters.dx;
  nx = parameters.nx;
  Xo = parameters.Xo;
  kappa = parameters.kappa;
  Ba = parameters.Ba;
  Bb = parameters.Bb;
  Fxo = parameters.Fxo;
  Fzo = parameters.Fzo;
  sr = parameters.sr;
  betavar = parameters.beta;
  faulttype = parameters.faulttype;
  L = parameters.L;
  dt = parameters.dt;
  lbc = parameters.lbc;
  rbc = parameters.rbc;
  lbctype = parameters.lbctype;
  rbctype = parameters.rbctype;
  t = parameters.t;
  modeluptodate = parameters.modeluptodate;
  profuptodate = parameters.profuptodate;
  bruptodate = parameters.bruptodate;
  icprofutd = parameters.icprofutd;
  icbrutd = parameters.icbrutd;
  x = parameters.x;
  importxprof = parameters.importxprof;
  importzprof = parameters.importzprof;
  importxbr = parameters.importxbr;
  importzbr = parameters.importzbr;
  Profile = parameters.Profile;
  Bedrock = parameters.Bedrock;
  ResultsProfile = parameters.ResultsProfile;
  ResultsBedrock = parameters.ResultsBedrock;
  ProfileInitCond = parameters.ProfileInitCond;
  BedrockInitCond = parameters.BedrockInitCond;

  PenckFile = parameters.PenckFile;

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

%----------------------
function importtopo(mainfig)

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

filename = uigetfile('*.xz');
if(filename ~= 0)
  fid = fopen(filename,'r');

  counter = 1;

  while(~feof(fid))
    line = fgetl(fid);
    data = sscanf(line,'%f %f');
    if(length(data) == 2)
      x(counter) = data(1);
      Profile(counter) = data(2);
      counter = counter + 1;
    end
  end

  parameters.importxprof = x;
  parameters.importzprof = Profile;

  set(mainfig,'UserData',parameters);
  fclose(fid);
end

%---------------------
function importbr(mainfig)

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

filename = uigetfile('*.xb');
if(filename ~= 0)
  fid = fopen(filename,'r');

  counter = 1;

  while(~feof(fid))
    line = fgetl(fid);
    data = sscanf(line,'%f %f');
    if(length(data) == 2)
      x(counter) = data(1);
      Bedrock(counter) = data(2);
      counter = counter + 1;
    end
  end

  parameters.importxbr = x;
  parameters.importzbr = Bedrock;

  set(mainfig,'UserData',parameters);
  fclose(fid);
end

%----------------------
function importtopobr(mainfig)

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

filename = uigetfile('*.xzb');
if(filename ~= 0)
  fid = fopen(filename,'r');

  counter = 1;

  while(~feof(fid))
    line = fgetl(fid);
    data = sscanf(line,'%f %f %f');
    if(length(data) == 3)
      x(counter) = data(1);
      Profile(counter) = data(2);
      Bedrock(counter) = data(3);
      counter = counter + 1;
    end
  end

  parameters.importxprof = x;
  parameters.importzprof = Profile;
  parameters.importxbr = x;
  parameters.importzbr = Bedrock;

  set(mainfig,'UserData',parameters);

  fclose(fid);

end

%----------------------
function exportparams(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
filename = uiputfile('*.pout');
if(filename ~= 0)
  typeflag = 0;
  times = [];
  exportdata(parameters,typeflag,times,filename);
end

%----------------------
function exportseltopo(mainfig)

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

if(parameters.modeluptodate)
  tlist = make_stringcell(parameters.t);
  [times,ok] = listdlg('PromptString','Model times to export:', ...
     'SelectionMode','multiple','Name', ...
     'Model Times to Export...','OKString','Continue',...
     'ListString',tlist);
  if(ok)
    filename = uiputfile('*.pout');
    if(filename ~= 0)
      typeflag = 1;
      exportdata(parameters,typeflag,times,filename);
    end
  end
else
  errordlg('Model is not up to date.  Rerun model before exporting results.','Export Error');
end
  
%----------------------
function exportselbr(mainfig)

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

if(parameters.modeluptodate)
  tlist = make_stringcell(parameters.t);
  [times,ok] = listdlg('PromptString','Model times to export:', ...
     'SelectionMode','multiple','Name', ...
     'Model Times to Export...','OKString','Continue',...
     'ListString',tlist);
  if(ok)
    filename = uiputfile('*.pout');
    if(filename ~= 0)
      typeflag = 2;
      exportdata(parameters,typeflag,times,filename);
    end
  end
else
  errordlg('Model is not up to date.  Rerun model before exporting results.','Export Error');
end

%----------------------
function exportsel(mainfig)

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

if(parameters.modeluptodate)
  tlist = make_stringcell(parameters.t);
  [times,ok] = listdlg('PromptString','Model times to output:', ...
     'SelectionMode','multiple','Name', ...
     'Model Times to Export...','OKString','Continue',...
     'ListString',tlist);
  if(ok)
    filename = uiputfile('*.pout');
    if(filename ~= 0)
      typeflag = 3;
      exportdata(parameters,typeflag,times,filename);
    end
  end
else
  errordlg('Model is not up to date.  Rerun model before exporting results.','Export Error');
end



%----------------------
function switchimportdata(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
importxprof = parameters.importxbr;
importzprof = parameters.importxbr;
importxbr = parameters.importxprof;
importzbr = parameters.importzprof;

parameters.importxbr = importxbr;
parameters.importzbr = importzbr;
parameters.importxprof = importxprof;
parameters.importzprof = importzprof;

parameters.profuptodate = 0;
parameters.bruptodate = 0;

set(mainfig,'UserData',parameters);

%----------------------
function interpolateprofileimport(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
x = parameters.x;
importx = parameters.importxprof;
importz = parameters.importzprof;

if(length(importx) == 0)
  errordlg('Profile data has not yet been imported.  Please load profile data before proceeding by using the File-->Import functions.', ...
   'Profile gridding error...');
elseif(length(importx) < 2)
  errordlg('Not enough points to perform interpolation.', ...
   'Profile gridding error...');
else
  if(min(importx) > min(x))
    i = find(min(importx) == importx);
    importx(end+1) = min(x);
    importz(end+1) = importz(i);
  end

  if(max(importx) < max(x))
    i = find(max(importx) == importx);
    importx(end+1) = max(x);
    importz(end+1) = importz(i);
  end

  [importx,i] = sort(importx);
  importz = importz(i);
  Profile = interp1(importx,importz,x,'linear');
  parameters.Profile = Profile;
  parameters.profuptodate = 1;
  set(mainfig,'UserData',parameters);
end

%----------------------
function interpolatebedrockimport(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
x = parameters.x;
importx = parameters.importxbr;
importz = parameters.importzbr;

if(length(importx) == 0)
  errordlg('Bedrock data has not yet been imported.  Please load bedrock data before proceeding by using the File-->Import functions.', ...
   'Bedrock gridding error...');
elseif(length(importx) < 2)
  errordlg('Not enough points to perform interpolation.', ...
   'Bedrock gridding error...');
else
  if(min(importx) > min(x))
    i = find(min(importx) == importx);
    importx(end+1) = min(x);
    importz(end+1) = importz(i);
  end

  if(max(importx) < max(x))
    i = find(max(importx) == importx);
    importx(end+1) = max(x);
    importz(end+1) = importz(i);
  end

  [importx,i] = sort(importx);
  importz = importz(i);
  Bedrock = interp1(importx,importz,x,'linear');
  parameters.Bedrock = Bedrock;
  parameters.bruptodate = 1;
  set(mainfig,'UserData',parameters);
end

%----------------------
function flattopo(mainfig)

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

parameters.ProfileInitCond = zeros(1,length(parameters.x));
set(mainfig,'UserData',parameters);
checkic;
parameters = get(mainfig,'UserData');
parameters.icprofutd = 1;
set(mainfig,'UserData',parameters);

%------------------------
function slopetopo(mainfig)

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

answer = inputdlg({'Enter the angle of rotation (in degrees):'},'Sloping Initial Topography...',1,{'0'});
if(sum(isletter(answer{1})) > 0 | isempty(answer))
  errordlg('Invalid surface slope','Surface Slope Error...');
else
  fee = tan(str2num(answer{1})*pi/180);
  parameters.ProfileInitCond = parameters.x.*sin(fee);
  set(mainfig,'UserData',parameters);
  checkic;
  parameters = get(mainfig,'UserData');
  parameters.icprofutd = 1;
  set(mainfig,'UserData',parameters);
end

%----------------------
function gridproftoprofile(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
if(parameters.profuptodate == 0)
  errordlg('Gridded profile data is not up to date with current settings.  Regrid Imported Profile Data (Edit-->Sort and Grid Import Data) before applying to initial profile.','Error applying gridded data to initial condition...')
else
  parameters.ProfileInitCond = parameters.Profile;
  set(mainfig,'UserData',parameters);
  checkic;
  parameters = get(mainfig,'UserData');
  parameters.icprofutd = 1;
  set(mainfig,'UserData',parameters);
end

%----------------------
function gridbrtobr(mainfig)

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
if(parameters.bruptodate == 0)
  errordlg('Gridded bedrock data is not up to date with current settings.  Regrid Imported Profile Data (Edit-->Sort and Grid Import Data) before applying to initial profile.','Error applying gridded data to initial condition...')
else
  parameters.BedrockInitCond = parameters.Bedrock;
  set(mainfig,'UserData',parameters);
  checkic;
  parameters = get(mainfig,'UserData');
  parameters.icbrutd = 1;
  set(mainfig,'UserData',parameters);
end

%----------------------
function profiletoinitialprofile(mainfig)

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

if(parameters.modeluptodate == 0)
  errordlg('Model is not up to date.  Run model to create profile.')
else
  if(length(parameters.ResultsProfile(end,:)) ~= length(parameters.x))
    errordlg('Model is not up to date.  Run model to create profile.');
  else
    parameters.ProfileInitCond = ResultsProfile(end,:);
    set(mainfig,'UserData',parameters);
    checkic;
    parameters = get(mainfig,'UserData');
    parameters.icprofutd = 1;
    set(mainfig,'UserData',parameters);
  end
end

%----------------------
function bedrocktoinitialbedrock(mainfig)

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

if(parameters.modeluptodate == 0)
  errordlg('Model is not up to date.  Run model to create profile.')
else
  if(length(parameters.ResultsBedrock(end,:)) ~= length(parameters.x))
    errordlg('Model is not up to date.  Run model to create profile.');
  else
    parameters.BedrockInitCond = ResultsBedrock(end,:);
    set(mainfig,'UserData',parameters);
    checkic;
    parameters = get(mainfig,'UserData');
    parameters.icbrutd = 1;
    set(mainfig,'UserData',parameters);
  end
end

%----------------------
function profiletoinitialbedrock(mainfig)

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

if(parameters.modeluptodate == 0)
  errordlg('Model is not up to date.  Run model to create profile.')
else
  if(length(parameters.ResultsProfile(end,:)) ~= length(parameters.x))
    errordlg('Model is not up to date.  Run model to create profile.');
  else
    parameters.BedrockInitCond = ResultsProfile(end,:);
    set(mainfig,'UserData',parameters);
    checkic;
    parameters = get(mainfig,'UserData');
    parameters.icbrutd = 1;
    set(mainfig,'UserData',parameters);
  end
end

%----------------------
function bedrocktoinitialprofile(mainfig)

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

if(parameters.modeluptodate == 0)
  errordlg('Model is not up to date.  Run model to create profile.')
else
  if(length(parameters.ResultsBedrock(end,:)) ~= length(parameters.x))
    errordlg('Model is not up to date.  Run model to create profile.');
  else
    parameters.ProfileInitCond = ResultsBedrock(end,:);
    set(mainfig,'UserData',parameters);
    checkic;
    parameters = get(mainfig,'UserData');
    parameters.icprofutd = 1;
    set(mainfig,'UserData',parameters);
  end
end

%----------------------
function offsetprofile(mainfig)

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

if(parameters.icprofutd == 0)
  errordlg('Profile Elevations are not up to date.  Set profile elevations using gridding functions (Edit menu) or copy bedrock elevations to profile (Initial Conditions menu).','Profile Gridding Error...');
else
  answer = inputdlg('Enter a uniform offset for the profile', ...
     'Uniform Profile Offset...',1,{'1'});
  if(sum(isletter(answer{1}) > 0))
    errordlg('Numeric input is required for this offset.','Input Error');
  else
    offset = str2num(answer{1});
    parameters.ProfileInitCond = parameters.ProfileInitCond + offset;
    set(mainfig,'UserData',parameters);
    checkic;
    parameters = get(mainfig,'UserData');
    parameters.icprofutd = 1;
    set(mainfig,'UserData',parameters);
  end
end

%----------------------
function offsetbedrock(mainfig)

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

if(parameters.icbrutd == 0)
  errordlg('Bedrock elevations are not up to date with Profile elevations.  Reset bedrock elevations using gridding functions (Edit menu) or copy profile elevations to bedrock (Initial Conditions menu).','Bedrock Gridding Error...');
else
  answer = inputdlg('Enter a uniform offset for the bedrock', ...
     'Uniform Bedrock Offset...',1,{'1'});
  if(sum(isletter(answer{1}) > 0))
    errordlg('Numeric input is required for this bedrock offset.','Input Error');
  else
    offset = str2num(answer{1});
    parameters.BedrockInitCond = parameters.BedrockInitCond + offset;
    set(mainfig,'UserData',parameters);
    checkic;
    parameters = get(mainfig,'UserData');
    parameters.icbrutd = 1;
    set(mainfig,'UserData',parameters);
  end
end

%----------------------
function profiletobedrock(mainfig)

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

parameters.BedrockInitCond = parameters.ProfileInitCond;
parameters.icbrutd = 1;

set(mainfig,'UserData',parameters);
 
%----------------------
function plotinitialconditions(mainfig)

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

if((parameters.icprofutd == 0) & (parameters.icbrutd == 0))
  errordlg('Initial Conditions are not up to date with current model settings.  Regrid input data and/or reset initial conditions before plotting.','Initial Conditions Plotting Error...');
else
  x = parameters.x;
  if(parameters.icprofutd == 1)
    ProfileInitCond = parameters.ProfileInitCond;
  end
  if(parameters.icbrutd == 1)  
    BedrockInitCond = parameters.BedrockInitCond;
  end

  fig = figure('Position',[400 300 600 600],'Resize','off','NumberTitle', ...
     'off', 'Name','Initial Conditions','Color',[1 1 1],'Colormap', ...
     gray(256),'Tag','InitialConditionsPlot');
  ax = axes('Parent',fig,'Units','Pixels','Position',[75 200 450 300]);

  axes(ax)
  g = gray(256);
  hold on
  if(parameters.icbrutd == 1)
    area(x,BedrockInitCond, ...
       (min(BedrockInitCond) - abs(0.25.*min(BedrockInitCond))), ...
       'FaceColor',g(220,:),'LineStyle','none');
    plot(x,BedrockInitCond,'k--');
  end
  if(parameters.icprofutd == 1)
    plot(x,ProfileInitCond,'k-');
  end
  title('Initial Conditions','FontSize',12,'FontWeight','bold','FontAngle', ...
     'italic');
  xlabel('Distance Along Profile','FontWeight','bold');
  ylabel('Elevation','FontWeight','bold');
  if(parameters.icbrutd == 1)
    miny = min(BedrockInitCond);
    maxy = max(BedrockInitCond);
  end
  if(parameters.icprofutd == 1)
    if(parameters.icbrutd == 0)
      miny = min(ProfileInitCond);
    end
    maxy = max(ProfileInitCond);
  end
  if(miny == maxy)
    miny = miny - 2;
    maxy = maxy + 2;
  end
  axis([min(x) max(x) miny-(0.25.*(maxy-miny)) maxy+(0.25.*(maxy-miny))]);

end

%----------------------
function plotfaultdisplacements(mainfig)

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

x = parameters.x;
if(strcmp(parameters.faulttype,'normal'))
  signdip = -1;
else
  signdip = 1;
end
beta = parameters.beta;
sr = parameters.sr.*signdip;
Fxo = parameters.Fxo;
Fzo = parameters.Fzo;
L = parameters.L;
roundednx = floor(parameters.nx./40);
i = 1:roundednx:parameters.nx;
xround = x(i);

[vx,vz] = computedisplacements(x,sr,beta,L,Fxo,Fzo);
vxround = vx(i);
vzround = vz(i);

fig = figure('Position',[400 300 600 600],'Resize','off','NumberTitle', ...
   'off', 'Name','Tectonic Displacements','Color',[1 1 1],'Colormap', ...
   gray(256),'Tag','TectonicDisplacementsPlot');
ax1 = axes('Parent',fig,'Units','Pixels','Position',[75 350 450 100]);
ax2 = axes('Parent',fig,'Units','Pixels','Position',[75 200 450 100]);
ax3 = axes('Parent',fig,'Units','Pixels','Position',[75 50 450 100], ...
   'YTick',[]);
ax4 = axes('Parent',fig,'Units','Pixels','Position',[425 475 100 100], ...
   'YTick',[],'XTick',[]);
ax5 = axes('Parent',fig,'Units','pixels','position',[355 160 90 20], ...
   'YTick',[],'XTick',[],'XColor',[1 1 1],'YColor',[1 1 1]);

axes(ax1)
plot(x,vx,'k-');
ylabel('V_x','FontWeight','bold');
axes(ax2)
plot(x,vz,'k-');
ylabel('V_z','FontWeight','bold');
maxv = max(max(abs(vz)));
s = 0.1.*(max(x)-min(x))./maxv;
axes(ax3)
quiver(xround,zeros(1,length(xround)),vxround.*s,vzround.*s,0,'k-')
xlabel('Distance Along Profile','FontWeight','bold');
axis equal;
ax3range = axis;
axis([min(x) max(x) ax3range(3) ax3range(4)])
axes(ax4)
betapl = beta;
if(betapl < 0)
  betapl = 180+betapl;
end
plot([Fxo (Fxo + L.*cos(betapl*pi/180))],[-Fzo ...
   -(Fzo + L.*sin(betapl*pi/180))],'k:')
hold on
plot(x,zeros(1,length(x)),'k-');
axis equal;
ax4range = axis;
minx = ax4range(1)-0.1.*(ax4range(2)-ax4range(1));
maxx = ax4range(2)+0.1.*(ax4range(2)-ax4range(1));
miny = ax4range(3)-0.1.*(ax4range(4)-ax4range(3));
maxy = ax4range(4)+0.1.*(ax4range(2)-ax4range(1));
axis([minx maxx miny maxy]);
set(ax4,'YTick',[],'XTick',[]);
axes(ax5)
quiver(0,0,(0.5.*maxv.*s),0,0,'k-')
axis([0 0.2*(max(x) - min(x)) -1 1])
set(ax5,'YTick',[],'XTick',[],'XColor',[1 1 1],'YColor',[1 1 1]);
uicontrol('Parent',fig,'Style','text','String', ...
   'Tectonic Displacements and Fault Geometry','FontSize',16,'FontWeight', ...
   'Bold','FontAngle','Italic','Position',[50 500 300 80], ...
   'BackgroundColor', [1 1 1]);
uicontrol('Parent',fig,'Style','text','String',strcat('=  ',num2str(0.5.*maxv)), ...
   'FontWeight','Bold','BackgroundColor',[1 1 1],'Position', ...
   [415 157 90 20],'HorizontalAlignment','left');


%----------------------
function plotfaultgeometry(mainfig)

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

if((parameters.icprofutd == 0) & (parameters.icbrutd == 0))
  errordlg('Initial Conditions are not up to date with current model settings.  Regrid input data and/or reset initial conditions before plotting.','Initial Conditions Plotting Error...');
else
  fig = figure('Position',[400 300 600 750],'Resize','off','NumberTitle', ...
     'off', 'Name','Fault Geometry and Initial Conditions','Color', ...
     [1 1 1],'Colormap',gray(256),'Tag','GeometryPlot');
  ax1 = axes('Parent',fig,'Units','Pixels','Position',[75 600 450 100]);
  ax2 = axes('Parent',fig,'Units','Pixels','Position',[75 50 450 450], ...
     'Box','off');

  axes(ax1)
  x = parameters.x;
  if(parameters.icprofutd == 1)
    ProfileInitCond = parameters.ProfileInitCond;
  end
  if(parameters.icbrutd == 1)  
    BedrockInitCond = parameters.BedrockInitCond;
  end

  g = gray(256);
  hold on
  if(parameters.icbrutd == 1)
    area(x,BedrockInitCond, ...
       (min(BedrockInitCond) - abs(0.25.*min(BedrockInitCond))), ...
       'FaceColor',g(220,:),'LineStyle','none');
    plot(x,BedrockInitCond,'k--');
  end
  if(parameters.icprofutd == 1)
    plot(x,ProfileInitCond,'k-');
  end
  title('Initial Conditions','FontSize',12,'FontWeight','bold','FontAngle', ...
     'italic');
  xlabel('Distance Along Profile','FontWeight','bold');
  ylabel('Elevation','FontWeight','bold');
  if(parameters.icbrutd == 1)
    miny = min(BedrockInitCond);
    maxy = max(BedrockInitCond);
  end
  if(parameters.icprofutd == 1)
    if(parameters.icbrutd == 0)
      miny = min(ProfileInitCond);
    end
    maxy = max(ProfileInitCond);
  end
  if(miny == maxy)
    miny = miny - 2;
    maxy = maxy + 2;
  end
  axis([min(x) max(x) miny-(0.25.*(maxy-miny)) maxy+(0.25.*(maxy-miny))]);

  Fxo = parameters.Fxo;
  Fzo = parameters.Fzo;
  L = parameters.L;
  beta = parameters.beta;

  axes(ax2)
  betapl = beta;
  if(betapl < 0)
    betapl = 180+betapl;
  end
  plot([Fxo (Fxo + L.*cos(betapl*pi/180))],[-Fzo ...
     -(Fzo + L.*sin(betapl*pi/180))],'k--')
  hold on
  plot(x,zeros(1,length(x)),'k-');
  axis equal;
  ax4range = axis;
  minx = ax4range(1)-0.1.*(ax4range(2)-ax4range(1));
  maxx = ax4range(2)+0.1.*(ax4range(2)-ax4range(1));
  miny = ax4range(3)-0.1.*(ax4range(4)-ax4range(3));
  maxy = ax4range(4)+0.1.*(ax4range(2)-ax4range(1));
  plot([minx maxx],[0 0],'k:');
  plot(x,zeros(1,length(x)),'k-')
  axis([minx maxx miny maxy]);
  set(ax2,'YTick',[],'Box','off');
  title('Fault Geometry','FontSize',12,'FontWeight','bold','FontAngle','italic');
  xlabel('Distance Along Profile','FontWeight','Bold');
  ylabel('Depth','FontWeight','Bold');
end

%----------------------
function runtlmodel(mainfig)

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

x = parameters.x;
nx = parameters.nx;
dx = parameters.dx;
dt = parameters.dt;
t = parameters.t;
totaltime = max(t);
LBC_TYPE = parameters.lbctype;
LBC = parameters.lbc;
RBC_TYPE = parameters.rbctype;
RBC = parameters.rbc;
kappa = parameters.kappa;
ProfileInitCond = parameters.ProfileInitCond;
if(strcmp(parameters.faulttype,'normal'))
  signdip = -1;
else
  signdip = 1;
end
sr = signdip.*parameters.sr;
Fxo = parameters.Fxo;
Fzo = parameters.Fzo;
beta = parameters.beta;
L = parameters.L;
icprofutd = parameters.icprofutd;

[vx,vz] = computedisplacements(x,sr,beta,L,Fxo,Fzo);
maxvx = max(abs(vx));

if(maxvx.*dt > dx)
  errordlg('Time step produces finite displacements greater than profile spacing.  Adjusting time step accordingly.  Rerun model','Transport Limited Model Error...');
  adjustment = dx./(maxvx.*dt);
  parameters.dt = dt.*adjustment.*0.95;
  set(mainfig,'UserData',parameters);

elseif(icprofutd == 0)
  errordlg('Initial Conditions not up to date with current model settings.  Regrid imported data or use the Initial Conditions menu to reset initial profile.','Transport Limited Model Error...');

else
  ResultsProfile(1,:) = ProfileInitCond;
  ResultsBedrock = [];
  waithandle = waitbar(0,'Transport Limited Model Running.  Please wait...');
  ResultsProfile(2,:) = p1d(x,nx,dx,dt,t(1),totaltime,LBC_TYPE,LBC, ...
     RBC_TYPE,RBC,vx,vz,kappa,ProfileInitCond,waithandle);
  for(i=2:length(t))
    ResultsProfile(i+1,:) = p1d(x,nx,dx,dt,t(i),totaltime,LBC_TYPE,LBC, ...
      RBC_TYPE,RBC,vx,vz,kappa,ResultsProfile(i,:),waithandle);
  end
  parameters.ResultsProfile = ResultsProfile;
  parameters.modeluptodate = 1;
  set(mainfig,'UserData',parameters);
  close(waithandle)
  msgbox('Transport Limited Model Finished!','Model Done.');
end

%----------------------
function runplmodel(mainfig)

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

x = parameters.x;
nx = parameters.nx;
dx = parameters.dx;
dt = parameters.dt;
t = parameters.t;
totaltime = max(t);
LBC_TYPE = parameters.lbctype;
LBC = parameters.lbc;
RBC_TYPE = parameters.rbctype;
RBC = parameters.rbc;
kappa = parameters.kappa;
ProfileInitCond = parameters.ProfileInitCond;
BedrockInitCond = parameters.BedrockInitCond;
if(strcmp(parameters.faulttype,'normal'))
  signdip = -1;
else
  signdip = 1;
end
sr = signdip.*parameters.sr;
Fxo = parameters.Fxo;
Fzo = parameters.Fzo;
beta = parameters.beta;
L = parameters.L;
Ba = parameters.Ba;
Bb = parameters.Bb;
icprofutd = parameters.icprofutd;
icbrutd = parameters.icbrutd;

[vx,vz] = computedisplacements(x,sr,beta,L,Fxo,Fzo);
maxvx = max(abs(vx));

if(maxvx.*dt > dx)
  errordlg('Time step produces finite displacements greater than profile spacing.  Adjusting time step accordingly.  Rerun model','Production Limited Model Error...');
  adjustment = dx./(maxvx.*dt);
  parameters.dt = dt.*adjustment.*0.95;
  set(mainfig,'UserData',parameters);
  refreshfigure;

elseif((icprofutd+icbrutd) < 2)
  errordlg('Initial Conditions not up to date with current model settings.  Regrid imported data or use the Initial Conditions menu to reset initial profile and bedrock.','Production Limited Model Error...');

else
  ResultsProfile(1,:) = ProfileInitCond;
  ResultsBedrock = BedrockInitCond;
  waithandle = waitbar(0,'Production Limited Model Running.  Please wait...');
  [ResultsProfile(2,:),ResultsBedrock(2,:)]= p1dpl(x,nx,dx,dt,t(1),totaltime,LBC_TYPE,LBC, ...
     RBC_TYPE,RBC,vx,vz,kappa,Ba,Bb,ProfileInitCond,BedrockInitCond,waithandle);
  for(i=2:length(t))
    [ResultsProfile(i+1,:),ResultsBedrock(i+1,:)] = p1dpl(x,nx,dx,dt,t(i),totaltime,LBC_TYPE,LBC, ...
      RBC_TYPE,RBC,vx,vz,kappa,Ba,Bb,ResultsProfile(i,:),ResultsBedrock(i,:), ...
      waithandle);
  end
  parameters.ResultsProfile = ResultsProfile;
  parameters.ResultsBedrock = ResultsBedrock;
  parameters.modeluptodate = 1;
  set(mainfig,'UserData',parameters);
  close(waithandle)
  msgbox('Production Limited Model Finished!','Model Done.');
end

%---------------------
function plotmodelresults(mainfig)

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

if(parameters.modeluptodate == 0)
  errordlg('Model results are not up to date with current model settings.  Rerun model (Tranport or Production Limited).','Model Results Plotting Error...');
else
  x = parameters.x;
  t = [0 parameters.t]; 
  
  fig = figure('Position',[400 300 600 400],'Resize','off','NumberTitle', ...
     'off', 'Name','Model Results','Color',[1 1 1],'Colormap', ...
     gray(256),'Tag','ResultsPlot');
  figdata.ax = axes('Parent',fig,'Units','Pixels','Position', ...
     [75 50 450 300],'Tag','ResultsAxis');
  tcell = make_stringcell(t);
  figdata.popup = uicontrol('parent',fig,'Style','popupmenu','String', ...
    tcell,'FontSize',12,'callback','penckgui changeresultfigt','Position', ...
    [425 350 100 20]);
  uicontrol('parent',fig,'Style','pushbutton','String', ...
    'No Vertical Exageration','FontSize',10,'callback','penckgui noexag', ...
    'Position',[200 350 150 20]);
  uicontrol('parent',fig,'Style','text','String','t = ', ...
    'HorizontalAlignment','left','FontSize',12,'Position',[375 350 50 20], ...
    'BackgroundColor',[1 1 1]);
  set(fig,'UserData',figdata);
  changeresultfigt;
end

%-----------------------------
function changeresultfigt(resultsfig)

mainfig = FigHandle;
fig = ResultsFigHandle;
figdata = get(fig,'UserData');
parameters = get(mainfig,'UserData');

ax = figdata.ax;
number = get(figdata.popup,'Value');
x = parameters.x;
ResultsProfile = parameters.ResultsProfile;
ResultsBedrock = parameters.ResultsBedrock;

axes(ax);
cla(ax);
g = gray(256);
hold on
if(~isempty(ResultsBedrock))
  area(x,ResultsBedrock(number,:), ...
     (min(ResultsBedrock(number,:)) - abs(0.25.* ...
     min(ResultsBedrock(number,:)))), 'FaceColor',g(220,:),'LineStyle', ...
     'none');
  plot(x,ResultsBedrock(number,:),'k--');
end
plot(x,ResultsProfile(number,:),'k-');
xlabel('Distance Along Profile','FontWeight','bold');
ylabel('Elevation','FontWeight','bold');
if(~isempty(ResultsBedrock))
  miny = min(ResultsBedrock(number,:));
  maxy = max(ResultsProfile(number,:));
else
  miny = min(ResultsProfile(number,:));
  maxy = max(ResultsProfile(number,:));
end
if(miny == maxy)
  miny = miny - 2;
  maxy = maxy + 2;
end
axis([min(x) max(x) miny-(0.25.*(maxy-miny)) maxy+(0.25.*(maxy-miny))]);

%----------------------
function noexag(resultsfig)

fig = ResultsFigHandle;
figdata = get(fig,'UserData');

ax = figdata.ax;
axes(ax)
range = axis;
ydivide = ((range(2)-range(1))-(range(4)-range(3)))./2;
axis([range(1) range(2) range(3)-ydivide range(4)+ydivide]);


%----------------------
function checkic(mainfig)

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

ProfileInitCond = parameters.ProfileInitCond;
BedrockInitCond = parameters.BedrockInitCond;

if((length(BedrockInitCond) == length(ProfileInitCond)) & ...
   (sum(ProfileInitCond <= BedrockInitCond) > 0))
  answer = questdlg('Some bedrock points are higher than the topography.  How should these points be treated?', 'Interpolation Problem...','Elevation-->Bedrock','Bedrock-->Elevation','Bedrock-->Elevation')
  if(strcmp(answer,'Bedrock-->Elevation'))
    BedrockInitCond = (BedrockInitCond > ProfileInitCond).*ProfileInitCond + (BedrockInitCond <= ProfileInitCond).*parameters.BedrockInitCond;
   else
    ProfileInitCond = (BedrockInitCond > ProfileInitCond).*BedrockInitCond + (BedrockInitCond <= ProfileInitCond).*ProfileInitCond;
   end
end

parameters.ProfileInitCond = ProfileInitCond;
parameters.BedrockInitCond = BedrockInitCond;

set(mainfig,'UserData',parameters);

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

mainfig = FigHandle;
parameters = get(mainfig,'UserData');
set(parameters.dxeditbox,'String',num2str(parameters.dx));
set(parameters.nxeditbox,'String',num2str(parameters.nx));
set(parameters.xoeditbox,'String',num2str(parameters.Xo));
set(parameters.dteditbox,'String',num2str(parameters.dt));
set(parameters.timeeditbox,'String',make_commadelimitedarray(parameters.t));
set(parameters.lbctypepopup,'Value',parameters.lbctype+1);
set(parameters.rbctypepopup,'Value',parameters.rbctype+1);
set(parameters.lbceditbox,'String',num2str(parameters.lbc));
set(parameters.rbceditbox,'String',num2str(parameters.rbc));
if(strcmp(parameters.faulttype,'normal'))
  set(parameters.typepopup,'Value',1)
else
  set(parameters.typepopup,'Value',2)
end
set(parameters.Fxoeditbox,'String',num2str(parameters.Fxo));
set(parameters.Fzoeditbox,'String',num2str(parameters.Fzo));
set(parameters.Leditbox,'String',num2str(parameters.L));
set(parameters.sreditbox,'String',num2str(parameters.sr));
set(parameters.betaeditbox,'String',num2str(parameters.beta));
set(parameters.kappaeditbox,'String',num2str(parameters.kappa));
set(parameters.Baeditbox,'String',num2str(parameters.Ba));
set(parameters.Bbeditbox,'String',num2str(parameters.Bb));


%----------------------
function recalculatex(mainfig)
mainfig = FigHandle;
parameters = get(mainfig,'UserData');
nx = parameters.nx;
dx = parameters.dx;
Xo = parameters.Xo;
parameters.x = Xo:dx:(nx-1).*dx+Xo;
set(mainfig,'UserData',parameters);

%----------------------
function A = get_commadelimitedarray(instring)

counter = 1;
while(~isempty(instring))
  [B S] = strtok(instring,',');
  if(sum(isletter(B)) == 0)
    A(counter) = str2num(B);
    counter = counter + 1;
  end
  instring = S;
end

A = sort(A);

%----------------------
function scell = make_stringcell(invector)

strg = [];
for(i=1:length(invector))
  strg = strvcat(strg,num2str(invector(i)));
end
scell = cellstr(strg);


%-----------------------
function instring = make_commadelimitedarray(A)

instring = '';
for(i=1:length(A))
  if(i < length(A))
    instring = strcat(instring,num2str(A(i)),',');
  else
    instring = strcat(instring,num2str(A(i)));
  end
end

%----------------------
function [vx,vz] = computedisplacements(x,b,dip,faultleng,xcoord,zcoord)
  
%  Compute displacements:

if(dip < 0)
  dip = 180+dip;
  b = -b;
end
omega = pi/2 - dip*(pi/180);
bx = b*sin(omega);
bz = b*cos(omega);
lowertipx = xcoord + sin(omega)*faultleng;
lowertipz = zcoord + cos(omega)*faultleng;
d1 = (x-xcoord)./(zcoord);
d2 = (x-lowertipx)./(lowertipz);
atand1 = atan2((x-xcoord),zcoord);
atand2 = atan2((x-lowertipx),lowertipz);
Ux1 = (-1/pi).*(bx.*atan(d1)+((bz - bx.*d1)./(1+d1.^2)));
Ux2 = (-1/pi).*(-bx.*atan(d2)+((-bz - -bx.*d2)./(1+d2.^2)));
Uz1 = (-1/pi).*(-bz.*atan(d1)+((-bx + -bz.*d1)./(1+d1.^2)));
Uz2 = (-1/pi).*(bz.*atan(d2)+((bx + bz.*d2)./(1+d2.^2)));
vx = Ux1 + Ux2;
vz = Uz1 + Uz2;


%----------------------------
function exportdata(parameters,typeflag,times,filename)

fid = fopen(filename,'W');

fprintf(fid,'dx = %4.3f, nx = %9i, Xo = %6.3f, kappa = %5.3f \n', ...
   parameters.dx,parameters.nx,parameters.Xo,parameters.kappa);
fprintf(fid,'Ba = %4.3f, Bb = %4.3f, Fxo = %4.3f, Fzo = %4.3f \n', ...
   parameters.Ba,parameters.Bb,parameters.Fxo,parameters.Fzo);
fprintf(fid,'sr = %4.3f, dip = %4.3f, fault type = %s, L = %4.3f \n', ...
   parameters.sr, parameters.beta, parameters.faulttype,parameters.L);
fprintf(fid,'dt = %4.3f, LBC = %4.3f, RBC = %4.3f, LBCTYPE = %i \n', ...
   parameters.dt, parameters.lbc, parameters.rbc,parameters.lbctype);
fprintf(fid,'RBCTYPE = %i \n',parameters.rbctype);

x = parameters.x;
ResultsProfile = parameters.ResultsProfile;
ResultsBedrock = parameters.ResultsBedrock;

if(typeflag == 1) % only elevation values:
  for(i=1:length(times))
    fprintf(fid,'t = %6.2f \n\n',parameters.t(i));
    fprintf(fid,'X               H\n');
    fprintf(fid,'-----------------\n');
    for(j=1:length(x))
      fprintf(fid,'%6.3f          %6.3f \n',x(j),ResultsProfile(i,j));
    end
    fprintf(fid,'\n\n==========================================');
  end
elseif(typeflag == 2) % only bedrock values:
  for(i=1:length(times))
    fprintf(fid,'t = %6.2f \n\n',parameters.t(i));
    fprintf(fid,'X               B\n');
    fprintf(fid,'-----------------\n');
    for(j=1:length(x))
      fprintf(fid,'%6.3f          %6.3f \n',x(j),ResultsBedrock(i,j));
    end
    fprintf(fid,'\n\n==========================================');
  end
elseif(typeflag == 3) % bedrock and profile values:
  for(i=1:length(times))
    fprintf(fid,'t = %6.2f \n\n',parameters.t(i));
    fprintf(fid,'X               H            B\n');
    fprintf(fid,'------------------------------\n');
    for(j=1:length(x))
      fprintf(fid,'%6.3f          %6.3f          %6.3f \n',x(j), ...
         ResultsProfile(i,j),ResultsBedrock(i,j));
    end
    fprintf(fid,'\n\n==========================================\n');
  end
end

fclose(fid);


