function h = i2thetaplot(s, varargin)
%SAXS/I2THETAPLOT
% Calculates I vs. 2 Theta curve from I vs. q curve. 
% Note that units are still intensity per mrad^2

x = 2*(asin((s.xaxisfull*s.wavelength)/(4*pi)))*180/pi;

%note since we are linear in q we are not linear in 2theta...may be a
%problem


%Karsten Joensen May 2012
%parameters required for calculating errorbars
% x is actually r
% y is theta

 
% calibrated
if s.kcal
    distance_units = '(Degrees)';   
else
    return
end
%do we know the time? if not 
if s.livetime
    if strcmp(s.reduction_state(1:2),'11')
        ylabeltext='Absolute intensity (cm^-1)';
    else
        ylabeltext='Average intensity (counts per mr^2 per second)';
    end
    livetime=s.livetime;
else
    ylabeltext='Average intensity during exposure (counts per mr^2)';
    livetime=1;
end
 
type = s.type;
switch type
    case 'r-ave'
        hplot = plot(x, s.pixels/livetime, varargin{:});% added by KJ April 12, 2005 normalizes;
        % shows aveage number of counts per mr^2 per second
        
        lastline=findobj(gcf,'Type','line');  %This returns all the lines in the plot but last is always element number 1
        set(lastline(1),'UserData',s); %saving saxsobj in data in the UserData variable
        set(lastline(1),'Tag','Data'); %so we can find it later when we want to change display
% this seems to work for both new and added lines.
        axes(get(hplot, 'Parent'));
        xlabel(['2-Theta, ', distance_units])
        ylabel(ylabeltext)
        %xdata=get(hplot,'Xdata');
        %xdatanew=xdata;
        %ydata=get(hplot,'Ydata');
        %ydatanew=ydata;

    
    case 'th-ave' % should not happen
        errordlg('This plottype does not apply to Azimuthal averages')
    case 'x-ave'
        hplot = plot(x, s.pixels/livetime, varargin{:});
        axes(get(hplot, 'Parent'));
        xlabel(['x, ', distance_units])
        ylabel(ylabeltext)
    case 'y-ave'
        hplot = plot(x, s.pixels/livetime, varargin{:});
        axes(get(hplot, 'Parent'));
        xlabel(['y, ', distance_units])
        ylabel(ylabeltext)
    otherwise
        error('This is the wrong type of SAXS image for PLOT.  Try IMAGE.')
end

% now preparing the graph for later manipulation. Foe each data line  we
% will 
% calculate the Error (std)
% put it in the appropriate saxs-obj
% call it a "1D-data" line so we can specifically find it later
% so that we can "pull" this data from the graph.

if nargout
    h = hplot;
end
