function buildquery()
%BUILDQUERY SQL statement builder.
%   BUILDQUERY builds an SQL statement for execution in the given
%   database.

%   Author(s): C.F.Garvin, 04-23-98
%   Copyright (c) 1984-2000 The MathWorks, Inc.
%   $Revision: 1.8 $   $Date: 2000/01/20 14:06:44 $

%Get the selected fields
fobj = findobj('Tag','fields');
fdat = get(fobj,{'String','Value'});
fstr = fdat{1}(fdat{2});

if isempty(fstr) | isempty(fdat{2})    %Do not build query if no fields are selected
  return
end

fields = [];
for i = 1:length(fstr)-1
  fields = [fields fstr{i} ','];
end
if isempty(fields)
  i = 0;
end
fields = [fields fstr{i+1}]; 

%Get the selected table
tobj = findobj(gcf,'Tag','tables');
tdat = get(tobj,{'String','Value'});
table = {tdat{1}{tdat{2}}};

%Create table list for JOIN operation (more than one table selected)
tables = [];
for i = 1:length(table)-1
  tables = [tables table{i} ','];
end
if isempty(tables)
  i = 0;
end
tables = [tables table{i+1}];

%Get the ALL or DISTINCT keyword
aodobj = findobj(gcf,'Tag','AoD','Value',1);
selkey = get(aodobj,'Userdata');

%Build SELECT statement
s = ['SELECT '  selkey ' ' fields ' FROM ' tables];

%Append WHERE clauses if they exist
wcobj = findobj('Tag','whereclausedata');
wcdat = get(wcobj,'Userdata');
if ~isempty(wcdat) 
  if ~isempty(wcdat{1})
    wcstr = wcdat{1};     %Where clause strings
    w = [];
    for i = 1:length(wcstr)
      w = [w ' ' wcstr{i}];
    end
    s = [s ' WHERE' w];
  end
end

%Append GROUP BY clauses if they exist
gcobj = findobj('Tag','groupbyclausedata');
gcdat = get(gcobj,'Userdata');
if ~isempty(gcdat)
  if ~isempty(gcdat{1})
    gcstr = gcdat{1};
    g = [];
    for i = 1:length(gcstr)
      if isempty(g)
        g = [g ' ' gcstr{i}];
      else
        g = [g ', ' gcstr{i}];
      end
    end
    s = [s ' GROUP BY' g];
  end    
end

%Append HAVING clause if it exists
hcobj = findobj('Tag','havingclausedata');
hcdat = get(hcobj,'Userdata');
if ~isempty(hcdat)
  if ~isempty(hcdat{1})
    hcstr = hcdat{1};
    h = [];
    for i = 1:length(hcstr)
      h = [h ' ' hcstr{i}];
    end
    s = [s ' HAVING' h];
  end
end

%Append ORDER BY clauses if they exist
ocobj = findobj('Tag','orderbyclausedata');
ocdat = get(ocobj,'Userdata');
if ~isempty(ocdat)
  if ~isempty(ocdat{1})
    ocstr = ocdat{1};
    o = [];
    for i = 1:length(ocstr)
      if isempty(o)
        o = [o ' ' ocstr{i}];
      else
        o = [o ', ' ocstr{i}];
      end
    end
    s = [s ' ORDER BY' o];
  end    
end

%Perform error checking for bad clause data
eflag = querycallbacks('errors');

%Display SQL statement
qobj = findobj('Tag','query');
set(qobj,'String',s)

%Set saveflag to prompt user for unsaved data
set(findobj(gcf,'Tag','saveflag'),'Value',1)

%Reset dialog name, removing loaded query name if present
set(findobj('Tag','SQLDLG'),'Name','Visual Query Builder')
