% get_data          - Save IOC buffer to file, copy over and read in
%
% Copyright (c) 2006 Dimtel, Inc., All Rights Reserved
%
% $Id: get_data.m,v 1.4 2017/05/07 09:25:35 dim Exp $
% $Date: 2017/05/07 09:25:35 $
% $Author: dim $
% $Revision: 1.4 $
% $Log: get_data.m,v $
% Revision 1.4  2017/05/07 09:25:35  dim
% Updated to better avoid race conditions in waiting for new waveforms
%
% Revision 1.3  2011/11/02 21:25:07  dim
% Optimized data PV retrieval, fixed gden bit for FPGA rev. 3.04+
%
% Revision 1.2  2011/10/20 16:59:40  dim
% Support for new data acquisition (FPGA rev. 3.04)
%
% Revision 1.1.1.1  2010/10/05 16:43:01  dim
% Initial import of iGp12
%
% Revision 1.2  2008/04/29 19:54:53  dim
% Transitioned from wget to urlwrite(), DCCT support, added FE/BE channels
% to saved parameters list.
%
% Revision 1.1  2007/10/28 08:23:15  dim
% Tools to include in the distribution
%
% Revision 1.1  2007/03/14 08:35:58  dim
% Matlab tools for data acquisition and testing with file-based data exchange
%
%

function x = get_data(pvroot, acq_unit)

fpga_rev = lcaGet([pvroot, 'REVISION']);

if (nargin == 1)
  acq_unit = 'BRAM'; % Default to BRAM for quicker transfers
end

if (fpga_rev >= 3.04)
  % Completely new model!!!

  % Redone in 2017 to monitor ACQ_ID
  aid = [pvroot, acq_unit, ':RAW:ACQ_ID'];
  % Set a monitor on acquisition ID
  lcaSetMonitor(aid);
  % Wait for the monitor (old ID)
  lcaNewMonitorWait(aid);
  % Read out stale ID
  lcaGet(aid);

  % Trigger dump
  lcaPut([pvroot, acq_unit, ':DUMP'], 1);
  % Wait for acquisition ID to update
  lcaNewMonitorWait(aid);
  [id, ts_id] = lcaGet(aid);
  [n, ts_n]   = lcaGet([pvroot, acq_unit, ':RAW:SAMPLES']);
  [x, ts_x]   = lcaGet([pvroot, acq_unit, ':RAW'], n);
%  fprintf('id = %d, ts_id = %.4f, ts_n = %.4f, ts_x = %.4f\n', id, ...
%          imag(ts_id)/1e9, imag(ts_n)/1e9, imag(ts_x)/1e9);
  lcaClear(aid);
else
  % Save the data
  lcaPut([pvroot, 'DATARD'], 1);
  lcaPut([pvroot, 'DATARD'], 0);
  ip = lcaGet([pvroot, 'IP_ADDR']);

  urlwrite(['http://', ip{1}, '/acq.dat'], 'acq.dat');
  fid = fopen('acq.dat');
  if (fpga_rev < 3)
    [x, count] = fread(fid, inf, 'int8');
  else
    [x, count] = fread(fid, inf, 'int16');
  end
  fclose(fid);
  x = x';
  system('rm acq.dat');
end
