function swrite(data_structure,new_history_file)
% swrite(data_structure,new_history_file ) keyword: SEPlib
%
% writes the structure containing all the information on the data onto a 
% history file and a binary file
% see also: from_history, load_data, load_history, read_vector, seminar,
% sep_dimensions, sep_read, sread
%
% input: a structure and a string, the string should contain the extension 
% output: nothing in Matlab workspace, just writes files
% a history file in the current directory, and a binary in scratch
%
% This function will only write real (esize=4) and complex (esize=8) data
% If data_format is anything else than 'xdr_float', it will abort execution.

[status1,user]=unix('whoami');user(length(user))=[];
[status2,hostname]=unix('hostname');hostname(length(hostname))=[];
new_scratch_file=data_structure.in;
% new_scratch_file=strcat('/net/koko/scr2/',user,'/',new_history_file,'@');

command=strcat('! cp .',data_structure.history_file,'. .',new_history_file);
command(6)=[];
command(6+length(data_structure.history_file))=[];
command(7+length(data_structure.history_file))=[];
eval(command);

fid_new_hist=fopen(new_history_file,'at','ieee-be');
[status,whentime] = unix('date');
in=data_structure.in;
fprintf(fid_new_hist,strcat('\nSo far, this was the content of==>',data_structure.history_file));
fprintf(fid_new_hist,cat(2,'\nMatlab: ',user,'@',hostname,' on ',whentime));
fprintf(fid_new_hist,cat(2,'\nsets next: in="',new_scratch_file,'"'));
for i=1:length(data_structure.n)
        fprintf(fid_new_hist,strcat('\n n',num2str(i),'=',num2str(data_structure.n(i))));
end
for i=1:length(data_structure.o)
        fprintf(fid_new_hist,strcat('\n o',num2str(i),'=',num2str(data_structure.o(i))));
end
for i=1:length(data_structure.d)
        fprintf(fid_new_hist,strcat('\n d',num2str(i),'=',num2str(data_structure.d(i))));
end
fprintf(fid_new_hist,strcat('\n esize','=',num2str(data_structure.esize)));
fprintf(fid_new_hist,strcat('\n data_format','="',num2str(data_structure.data_format),'"'));
fprintf(fid_new_hist,'\n End of Matlab-written history');
fclose(fid_new_hist);

fid_new_data=fopen(new_scratch_file,'w','ieee-be');

if data_structure.data_format =='xdr_float'
        if data_structure.esize == 4
                 count=fwrite(fid_new_data,data_structure.data,'float32');
         elseif data_structure.esize == 8
                tempreal=0;tempimag=0;countreal=0;countimag=0;
                for k=1:prod(size(data_structure.data))
                        tempreal=real(data_structure.data(k));
                        tempimag=imag(data_structure.data(k));
                        countreal=fwrite(fid_new_data,tempreal,'float32');
                        countimag=fwrite(fid_new_data,tempimag,'float32');
                end
        else
                disp('Data must be real (esize=4) or complex (esize=8)');
        end
else
        disp(strcat('Data type must be xdr_float, not ',loaded_history.data_format)); 
end
