function varargout = Holgerssample2(varargin)
% HOLGERSSAMPLE2 M-file for Holgerssample2.fig
%      HOLGERSSAMPLE2, by itself, creates a new HOLGERSSAMPLE2 or raises the existing
%      singleton*.
%
%      H = HOLGERSSAMPLE2 returns the handle to a new HOLGERSSAMPLE2 or the handle to
%      the existing singleton*.
%
%      HOLGERSSAMPLE2('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in HOLGERSSAMPLE2.M with the given input arguments.
%
%      HOLGERSSAMPLE2('Property','Value',...) creates a new HOLGERSSAMPLE2 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Holgerssample2_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Holgerssample2_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Holgerssample2

% Last Modified by GUIDE v2.5 17-Dec-2012 10:42:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Holgerssample2_OpeningFcn, ...
                   'gui_OutputFcn',  @Holgerssample2_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Holgerssample2 is made visible.
function Holgerssample2_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Holgerssample2 (see VARARGIN)

% Choose default command line output for Holgerssample2
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Holgerssample2 wait for user response (see UIRESUME)
% uiwait(handles.Mainfigure);


% --- Outputs from this function are returned to the command line.
function varargout = Holgerssample2_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function Abschnitsnummer_Callback(hObject, eventdata, handles)
% hObject    handle to Abschnitsnummer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Abschnitsnummer as text
%        str2double(get(hObject,'String')) returns contents of Abschnitsnummer as a double


% --- Executes during object creation, after setting all properties.
function Abschnitsnummer_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Abschnitsnummer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function Bemerkung_Callback(hObject, eventdata, handles)
% hObject    handle to Bemerkung (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Bemerkung as text
%        str2double(get(hObject,'String')) returns contents of Bemerkung as a double


% --- Executes during object creation, after setting all properties.
function Bemerkung_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Bemerkung (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in buttonstart.
function buttonstart_Callback(hObject, eventdata, handles)
% hObject    handle to buttonstart (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Curr_folder = pwd;
a = sprintf('%s%s', Curr_folder,'\PathData.txt');
fid = fopen(a, 'rt');
txt = '';
while ~strcmp(txt, '[Path]')
    txt = fgetl(fid);
end
PathConfigData = fscanf(fid, 'PathConfigData =   %s', 1);
fclose(fid);

Abschnitszahl = str2num(get(handles.Abschnitsnummer,'string'));

fid1 = fopen(PathConfigData, 'rt');
txt1 = '';
while ~strcmp(txt1, num2str(Abschnitszahl))
    txt1 = fgetl(fid1);
end
B = textscan(fid,'%s = %s', 4);
fclose(fid1);
Path = B{2};  
PathReference   = Path{1};
PathCoordinates = Path{2};
Pathresults     = Path{3};
Remarks         = Path{4};

set(handles.Bemerkung,'string',Remarks);

% interpolation happend now
% refrenzfeld_matrix wird erstellt

x_num_pixel = 27;
y_num_pixel = 27;
x_dist_in_mm = 10;
y_dist_in_mm = 10;

fid2 = fopen(PathReference ,'rt');
txt2 = '';
while ~strcmp(txt2, '[Referenzwerte]')
    txt2 = fgetl(fid2);
end
kf_mat = fscanf(fid2, '%f = %f', inf);
fclose(fid2);
kf_mat = kf_mat(2:2:end);
kf_mat = reshape(kf_mat, x_num_pixel, y_num_pixel);
kf_mat = flipud(kf_mat);


%Koordinate-System wird gelesen:
fid3 = fopen(PathCoordinates, 'rt');
txt3 = '';
while ~strcmp(txt3, ';Kanal-Nr. = Status(Aktiv/Inaktiv);A/D-Kanal(1-4);IF-KanalNr;X_0;Y_0;K-Faktor;"Bemerkung"')
txt3 = fgetl(fid3);
end
B = textscan(fid3, '%f = %s%f%f%f%f%f%s', 'delimiter', ';', 'MultipleDelimsAsOne', 1);
fclose(fid3);
x_array_in_mm = B{5};                                                           
y_array_in_mm = B{6};
property      = B{2};
AD_kanal      = B{3};
IF_kanal      = B{4};
Bemerkungen   = B{8};

num_pos = length(x_array_in_mm);
result =  -ones(num_pos, 1);

% umwandlung alle kordinatensystem(in mm) in index koordinatensystem

T_PB = [0 1 140; 1 0 140; 0 0 1];
T_IP = [1/x_dist_in_mm 0 0; 0 1/y_dist_in_mm 0; 0 0 1];


%billinear interpolation : hier sollten alle komponete von xI und yI
%interpoliert werden

for row_id = 1:num_pos
    x_I = T_IP * T_PB * [x_array_in_mm(row_id); y_array_in_mm(row_id); 1];
    cur_x = x_I(1);
    cur_y = x_I(2);
    if cur_x >= 0.5 && cur_x < x_num_pixel+0.5 && cur_y > 0.5 && cur_y < y_num_pixel+0.5 
        x0 = floor(cur_x);
        y0 = floor(cur_y);
        r = cur_x - x0;
        s = cur_y - y0;
        x01 = x0 + 1;
        y01 = y0 + 1;
        if x0 == 0
            x0 = 1;
        elseif x01 ==  x_num_pixel + 1
            x01 = x_num_pixel;
        end
        if y0 == 0
            y0 = 1;
        elseif y0 + 1 == y_num_pixel+1
            y01 = y_num_pixel;
        end

          if strcmp(property(row_id), 'Aktiv') == 1
             result(row_id, 1) = (1 - r) * (1 - s) * kf_mat(x0, y0) + ...
                                  (1 - r) *      s  * kf_mat(x0, y01) + ...
                                       r  * (1 - s) * kf_mat(x01, y0) + ...
                                       r  *      s  * kf_mat(x01, y01);
          else 
                   result(row_id) = -2;
          end
    end
end

%Ergebnisse in einer text datei schreiben
        
pfad_ref = 'G:\Daten\KuE\cvi5prue\pruef\monitor\Co60-1\ArrayCal\Referenzfeld\Referenzfeld_T10024_40.ini';
pfad_KS  = 'G:\Daten\KuE\cvi5prue\pruef\monitor\Co60-1\ArrayCal\Eigenschaften\Array_T10032.ini';
fid4 = fopen(Pathresults, 'wt');
fprintf(fid4, ';**********************************************************************\r\n');
fprintf(fid4, '; InterpolResultTemplate.txt\r\n');
fprintf(fid4, ';\r\n');
fprintf(fid4, '; erstellt: 			26.11.2012/Ge\r\n');
fprintf(fid4, ';\r\n');
fprintf(fid4, ';**********************************************************************\r\n\n');
fprintf(fid4, '[Info]\r\n');
fprintf(fid4, 'ErstelldatumRef = 16.01.2012\r\n');
fprintf(fid4, 'PfadReferenz = %s\r\n', pfad_ref);
fprintf(fid4, 'PfadKoordinaten = %s\r\n', pfad_KS);
fprintf(fid4, 'Array_Typen = T10032, T10043\r\n');
fprintf(fid4, 'Pruefplatz = Co60-1\r\n'); 
fprintf(fid4, 'ProgrammName = ArrayInterpol.exe\r\n');
fprintf(fid4, 'ProgrammVersion = 1.00\r\n\n\n');
fprintf(fid4, '[Kanal_Info]\r\n');
fprintf(fid4, ';Kanal-Nr. = Status(Aktiv/Inaktiv);A/D-Kanal(1-4);IF-KanalNr;X_0;Y_0;K-Faktor;"Bemerkung"\r\n\n');
for row_id = 1:num_pos
      fprintf(fid4, '%d = %s;%d;%d;%3f;%3f;%3f;%s\r\n',...
                  row_id-1, property{row_id}, AD_kanal(row_id), IF_kanal(row_id), x_array_in_mm(row_id), y_array_in_mm(row_id), result(row_id), Bemerkungen{row_id});
 end 
fclose(fid4); 

  
% % ergebnisse Darstellen
% 
% xI = (y_array_in_mm + 140)./ x_dist_in_mm; 
% yI = (x_array_in_mm + 140)./ y_dist_in_mm; 
% 
% figure(1); clf; hold on;
% plot3(x_array_in_mm, y_array_in_mm, result1, 'xb');
% plot3(xI, yI, result1, 'ok');
% grid on;
% xlabel('x_array_in_mm');
% ylabel('Y_array_in_mm');
% zlabel('result1');
% 
% title('Interpolate');

errorcode = 0





% --- Executes on button press in buttonexit.
function buttonexit_Callback(hObject, eventdata, handles)
% hObject    handle to buttonexit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
delete(handles.Mainfigure)
