% This file is used to overwrite existing data of a DICOM file
% The overwrite operation cannot be undone. Use with care.
% This script may contain errors or bugs.

ftest = 'SPECTRO_TESTSPB.MR.HERSENEN_GEAVANCEERD.0012.0001.2023.03.18.17.03.13.138090.215403695.IMA'; % DICOM file to overwrite
N = 1024; % number of sampling points

%return file pointer location and size to change
fda = dicom_open(ftest);
[complex_fid_dummy, position, field_size] = dicom_get_spectrum_siemens(fda) ; %modified function returning location and size of data

fclose(fda);

Nrow = sqrt((field_size/(N*2)));
Ncol = Nrow;

['If square, ',num2str(Nrow),' X ',num2str(Ncol), ' is the matrix size']

%%
%define new values as a N_row x Ncol x N matrix

NewData = zeros(Nrow,Ncol,N);


run('Wmet3Toff47G_2Hz.m');                %simulated data
DATAc = DATA(:,1)+1i.*(DATA(:,2));
DATAr = reshape(DATAc,[SIZE(1) SIZE(3)]);
% 
DATAr(:,4) =DATAr(:,4).*5;

fidt = conj(sum(DATAr,2));                      %Add peaks together
NewData(1,1,:) = fidt;                    %Fill in the voxel(s) with the simulated data


%%

answer = questdlg('Are you sure you want to overwrite file ',ftest', 'Yes', 'No','No');
if strcmpi(answer, 'Yes')

fd = fopen(ftest, 'r+','b');           %make this read/write (r+)
fseek(fd, position,'bof');             %The data starts here

fidtotal = reshape( permute(NewData,[3 2 1]),[field_size/2 1])';

myvals_real = single(imag(fidtotal) );
myvals_imag = single(real(fidtotal) );
kpo = 1;
for kp =1:2:field_size
  
        myvals(kp)=myvals_real(kpo);
        myvals(kp+1)=myvals_imag(kpo);

        kpo = kpo + 1;
end

for hty = 1:field_size
count = fwrite(fd,myvals(hty), 'float32','ieee-le');
end

fclose(fd);
['file has been overwritten']

else
   ['nothing was done']
end



