% BUILDQUERY build a query from the settings on the query panel
%
% M Hewitson
%
% $Id: buildquery.m,v 1.2 2011/04/08 08:56:37 hewitson Exp $
%
function buildquery(varargin)


  mainfig    = varargin{end};

  % Get number of conditions
  Nc  = mainfig.Nconditions;

  % Select fields
  fieldList = findobj(mainfig.handle, 'Tag', 'fieldsList');
  fieldsStr = get(fieldList, 'String');
  vals      = get(fieldList, 'Value');
  fields    = fieldsStr(vals);

  % Get table
  tableSel = findobj(mainfig.handle, 'Tag', 'tableSelect');
  tbls     = get(tableSel, 'String');
  tbl      = tbls{get(tableSel, 'Value')};

  % Start the query
  q = 'SELECT ';
  for j=1:length(fields)
    q = [q fields{j} ','];
  end
  q = [q(1:end-1) ' FROM ' tbl];


  for k=1:Nc

    if k==1
      q = [q ' WHERE '];
    end

    % get field
    h = findobj(mainfig.handle, 'Tag', sprintf('c%02dField', k));
    fields = get(h, 'String');
    field  = fields{get(h, 'Value')};

    q = [q field];

    % get condition
    h = findobj(mainfig.handle, 'Tag', sprintf('c%02dCondition', k));
    conds = get(h, 'String');
    cond  = conds{get(h, 'Value')};

    q = [q ' ' cond ' '];

    % get value
    h   = findobj(mainfig.handle, 'Tag', sprintf('c%02dValue', k));
    val = get(h, 'String');
    q = [q '"' val '"'];

    % Get compound
    if k<Nc

      h   = findobj(mainfig.handle, 'Tag', sprintf('c%02dCompound', k));
      comps = get(h, 'String');
      comp  = comps{get(h, 'Value')};

      q = [q ' ' comp ' '];

    end


  end

  % Order by
  h = findobj(mainfig.handle, 'Tag', 'fieldOrderBy');
  fields = get(h, 'String');
  field  = fields{get(h, 'Value')};

  q = [q ' ORDER BY ' field];

  h = findobj(mainfig.handle, 'Tag', 'sortDir');
  dirs = get(h, 'String');
  dir  = dirs{get(h, 'Value')};

  q = [q ' ' dir ';'];

  % Set query string on GUI
  h = findobj(mainfig.handle, 'Tag', 'queryDisplayTxt');
  set(h, 'String', q);

  drawnow
end
