function stat = cut_image2(dir,infilename,maxlat,len_l,minlon,wid_l,outfilename)

%%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
%inpifg: input interferogram to be cut
%header: header filename of the input ifg
%maxlat: maximum latitude of the output ifg
%len_l:  FILE_LENGTH of the output ifg
%minlon: minimum longitude of the output ifg
%wid_l:  WIDTH of the output ifg
%outfilename : filename of the output ifg
%%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

str=[dir,'/',infilename];
fid=fopen(str,'rb');
fid_header=fopen([str '.rsc'],'r');

header_src=textscan(fid_header,'%s%13.8f');
fclose(fid_header);

for i=1:length(header_src{1})
    name=char(header_src{1}(i));
   if(strcmp(name,'WIDTH')==1)
       width=header_src{2}(i);
       continue;
   end
   if(strcmp(name,'FILE_LENGTH')==1)
       len=header_src{2}(i);
       continue;
   end
   if(strcmp(name,'X_FIRST')==1)
       xfirst=header_src{2}(i);
   end
   if(strcmp(name,'Y_FIRST')==1)
       yfirst=header_src{2}(i);
       continue;
   end
   if(strcmp(name,'X_STEP')==1)
       xstep=header_src{2}(i);
       continue;
   end
   if(strcmp(name,'Y_STEP')==1)
       ystep=header_src{2}(i);
       continue;
   end
end

[data, count]=fread(fid,[width, len],'float');
data=data';
fclose(fid);

lat=zeros(len,width);
lon=zeros(len,width);

for i=1:len
    for j=1:width
      lat(i,j)=  yfirst +ystep*(i-1);
      lon(i,j)=  xfirst + xstep*(j-1);
    end
end

%find lat/lat range
index_maxlat=round((maxlat-yfirst)/ystep)+1;
index_minlat=index_maxlat+len_l-1;
index_minlon=round((minlon-xfirst)/xstep)+1;
index_maxlon=index_minlon+wid_l-1;

if(index_maxlat<1 || index_minlat>len)
    disp('cut_image: the input image is smaller than the output!');
    return;
end

if(index_minlon<1 || index_maxlon>width)
    disp('cut_image: the input image is smaller than the output!');
    return;
end

%index_minlat-index_maxlat;
%index_maxlon-index_minlon;

%lat_cut=lat(index_maxlat:index_minlat,index_minlon:index_maxlon);
%lon_cut=lon(index_maxlat:index_minlat,index_minlon:index_maxlon);
data_cut=data(index_maxlat:index_minlat,index_minlon:index_maxlon);




%output binary image
dem_out=data_cut';
fid=fopen([dir,'/',outfilename],'wb');
fwrite(fid,dem_out,'float');
fclose(fid);

w=fopen([dir,'/',outfilename,'.rsc'],'w');
fprintf(w,'WIDTH  %d\n',wid_l);
fprintf(w,'FILE_LENGTH   %d\n',len_l);
fprintf(w,'XMIN          0\n');
fprintf(w,'XMAX          %d\n',wid_l);
fprintf(w,'YMIN          0\n');
fprintf(w,'YMAX          %d\n',len_l);
fprintf(w,'X_FIRST       %13.8f\n',minlon);
fprintf(w,'Y_FIRST       %13.8f\n',maxlat);
fprintf(w,'X_STEP        %13.8f\n',xstep);
fprintf(w,'Y_STEP        %13.8f\n',ystep);
fprintf(w,'X_UNIT        degres\n');
fprintf(w,'Y_UNIT        degres\n');
fprintf(w,'Z_OFFSET      0\n');
fprintf(w,'Z_SCALE       1\n');
fprintf(w,'PROJECTION    LATLON\n');
fprintf(w,'DATUM         WGS84\n');
fclose(w);

stat=1;
