function [newngrid R]=downscale (varargin)
% call downscale (ngrid,newcelldist,offset,filetowrite,ext,numberoffiles)


    action=varargin{1};
    switch action       
        case 'attach_nest'
            load ('fireonly','firelist');
            firelist(:,[4:5])=[]; % die brauchen wir jetzt nicht            
            load ('Nesterov','Nestv');            
            firengridlat=round((firelist(:,1)*-0.5252+47.5-24)); % ab 28
            firengridlon=round((firelist(:,2)+360.9375)/1.875)-179;  % ab 179
            firengridlon(firengridlon==0)=1;
            firengridyear=floor((firelist(:,3)-19990000)/10000);
            firengridmonth=mod(floor((firelist(:,3))/100),100);
            daysofmonth=[0 31    59    90   120   151   181   212   243   273   304   334 ]';
            firengridday=daysofmonth(firengridmonth)+mod(((firelist(:,3))),100);
            clear ('firengridmonth','firetest')
            tic;
            size_1=size(Nestv,1);
            size_2=size(Nestv,2);
            size_3=size(Nestv,3);
            firenest=Nestv(firengridyear(:)+(firengridlon(:)-1)*size_1+(firengridlat(:)-1)*size_1*size_2+(firengridday(:)-1)*size_1*size_2*size_3);
            toc  
         save ('firenest');

         case 'read_nc_txt'
            %reads txtfiles and calculated the forward and backward Nesterov index and adds it to the fire list
            % achtung temp ist in Kelvin angegeeben also -273,15
            gesammtngrid=[];
        file=varargin{2};
        if isempty(strfind(file,'.txt')) % dann ist es ein Verzeichniss
            verz=dir(file);
        else
            verz(1).name=file;
            file='';
        end
        for i=1:size (verz,1)
            gesammtngrid=[];
            if ~isempty(strfind(verz(i).name,'.txt'))                    
                strcat('lese:',file,verz(i).name)
%                fid=fopen(strcat(file,verz(i).name));
%                 line=0;
%                 while 1 
%                     tline=fgetl(fid);
%                    
%                     if ~ischar(tline)
%                         break,
%                     else
%                         if (size(str2num(tline),2)==6)
%                             line=line+1;
%                             newngrid(line,:)=str2num(tline);
%                             
%                         end
%                     end
%                 end
%                 fclose (fid);
                newngrid =load(strcat(file,verz(i).name));
                
                if prod(size(newngrid))==3836880
%                     timesteps=varargin{3};
% %                     xdim=varargin{4};
% %                     ydim=varargin{5};
%                     xdim=144;%   temperature (192,94)  blitze(144,73)
%                     ydim=73;%
%                     timesteps=prod(size(newngrid))/144/73; % wegen
%                     Schaltjahr
%                      newngrid =reshape(newngrid',prod(size(newngrid)),1);
%                     newngrid =reshape(newngrid',xdim,ydim,timesteps);
%                     newngrid(145:184,:,:)=newngrid(1:40,:,:);
%                     %berechnung einer Postion
%                     %jede Zelle ist 2,5*2,5 start bei 0,0
%                     % also wenn negativ +360
%                     % sonst einfach alles/2.5 und fuer die latitude immer
%                     % plus 90 und durch 2.5 
%                     % hier wird die Karte einfach hoch geskaled..
%                     % beide haben den selben startpunkt...
%                     for i=i=size
                else
                    xdim=192;%144   temperature (192,94)  blitze(144,73)
                    ydim=94; %73
                    timesteps=prod(size(newngrid))/192/94; % wegen Schaltjahr
                    if mod(timesteps,1)~=0 
                        'dimensionen falsch'
                        return
                    end
                    newngrid =reshape(newngrid',prod(size(newngrid)),1);
                    newngrid =reshape(newngrid',xdim,ydim,timesteps);
                    % set africa zusammen                    
                    %newngrid(193:222,:,:)=newngrid(1:30,:,:);
                    newngrid(193:225,:,:)=newngrid(1:33,:,:);
                    
                    %newngrid=newngrid(185:221,29:66,:);        
                    newngrid=newngrid(180:225,25:75,:);        
                end                                       
                %und nun alle zusammen achtung schaltjahr,                               
                jahr=str2num(verz(i).name(findstr((strrep(verz(i).name,'.txt','')),'200'):findstr((strrep(verz(i).name,'.txt','')),'200')+3))
                alles(jahr-1999,:,:,1:365)=newngrid(:,:,1:365); % wegen schaltjahr
                save (strrep(verz(i).name,'.txt',''));     
            end 
        end     
    case 'calc_Nesterov'
     %   Nesterov: summiere alle 
     tic
   load Africa_temp_prec
   load ('Africa_ncep_land','land')
   landv(1,:,:,1)=land;
   landv(landv==0)=NaN;
%       if ((dprec[d]<=3) & ((dtemp_min[d]-4)>=0))
%         d_NI=dtemp_max[d]*(dtemp_max[d]-dtemp_min[d]-4);
%    
%     else
%         d_NI=0;
%      
%     if ( d_NI>0)
%         ni_acc=ni_acc+d_NI;
%     else
%         ni_acc=0;   
dew=zeros(size(air));
Nestv=zeros(size(air));
Nestk=zeros(size(air));
dew=(237.7*(17.27.*air)./(237.7+air)+log(rhum./100))./(17.27-((17.27*air)./(237.7+air)+log(rhum./100)));    % Taupunkt aus der Mitteltemperatur
Nestvt=(air-dew).*air;

% if ((dprec[d]<=3) & ((dtemp_min[d]-4)>=0))
%         d_NI=dtemp_max[d]*(dtemp_max[d]-dtemp_min[d]-4);   		
%     else
%         d_NI=0.;
    
for jahr=1:7
    jahr
    for tag=1:365       
        if tag>1
            Nestk(jahr,:,:,tag)=max(0,tmax(jahr,:,:,tag).*(tmax(jahr,:,:,tag)-tmin(jahr,:,:,tag)-4)+Nestk(jahr,:,:,tag-1));                       
            Nestv(jahr,:,:,tag)=Nestvt(jahr,:,:,tag)+Nestv(jahr,:,:,tag-1);
            Nestv(prec>3)=0;                              
            Nestk(prec>3)=0;                              
        else
            if jahr>1
                Nestk(jahr,:,:,tag)=max(0,tmax(jahr,:,:,tag).*(tmax(jahr,:,:,tag)-tmin(jahr,:,:,tag)-4)+Nestk(jahr-1,:,:,365));                       
                Nestv(jahr,:,:,tag)=Nestvt(jahr,:,:,tag)+Nestv(jahr-1,:,:,365);
                Nestk(prec>3)=0;                            
                Nestv(prec>3)=0;                            
            else
                Nestk(jahr,:,:,tag)=max(0,tmax(jahr,:,:,tag).*(tmax(jahr,:,:,tag)-tmin(jahr,:,:,tag)-4));
                Nestk(prec>3)=0;                            
                Nestv=Nestvt;
                Nestv(prec>3)=0;                            
            end
        end
       
     %    Nestv(Nestv>6000)=6000;
        end
     end
     for jahr=1:7
         for tag=1:365
             Nestv(jahr,:,:,tag)=Nestv(jahr,:,:,tag).*landv(1,:,:,1);
             Nestk(jahr,:,:,tag)=Nestk(jahr,:,:,tag).*landv(1,:,:,1);
         end
     end               
     save('Nesterov','Nestv','Nestk');
   
     toc               
    
        
        
        case  'rhum'
            %reads txtfiles and converts rhum in correct format
            
            gesammtngrid=[];
        file=varargin{2};
        if isempty(strfind(file,'.txt')) % dann ist es ein Verzeichniss
            verz=dir(file);
        else
            verz(1).name=file;
            file='';
        end
        for i=1:size (verz,1)
            gesammtngrid=[];
            if ~isempty(strfind(verz(i).name,'.txt'))                    
                strcat('lese:',file,verz(i).name)
                newngrid =load(strcat(file,verz(i).name));
                
                if nargin>2
                    timesteps=varargin{3};
                    xdim=varargin{4};
                    ydim=varargin{5};
                else
                    xdim=192;%144   temperature (192,94)  blitze(144,73)
                    ydim=94; %73
                    timesteps=prod(size(newngrid))/192/94; % wegen Schaltjahr
                    if mod(timesteps,1)~=0 
                        'dimensionen falsch'
                        size(newngrid)
                        return
                    end
                end               
                newngrid =reshape(newngrid',prod(size(newngrid)),1);
                newngrid =reshape(newngrid',xdim,ydim,timesteps);
                %interpolate to 1 degree ngrid first for whole world
                % interpolation is always with a line of NaNs at the edge,
                % thats why we first concentate
                newngrid=[newngrid; newngrid(1:xdim/2,:,:)];
                newngrid(1:xdim/2,:,:)=[];
%               
                [Xo,Yo] = meshngrid(180/ydim/2:180/ydim:180-(180/ydim/2),360/xdim/2:360/xdim:360-(360/xdim/2));
                [Xn,Yn] = meshngrid(0.5:179.5,0.5:359.5);
                for day=1:size(newngrid,3) % gets
                    int(:,:,day)=interp2(Xo,Yo,squeeze(newngrid(:,:,day)),Xn,Yn);
                end
               
%                 and now to the CAMIC ngrid: 
%                 Grid:
%                 1 x 1 degree
% 
                 longitude=[-20.5, +55.5];
                 latitude=[	+38.5, -36.5];
                 clear 'newngrid';
                 newngrid=int(180.5+longitude(1):180.5+longitude(2),(90.5-latitude(1):90.5-latitude(2)),:);
                  
%                 % set africa zusammen
%                 newngrid(193:222,:,:)=newngrid(1:30,:,:);
%                 newngrid=newngrid(185:221,29:66,:);        
%                 gesammtngrid(:,:,size(gesammtngrid,3)+1:size(gesammtngrid,3)+size(newngrid,3))=newngrid; 
%                 save (strrep(verz(i).name,'.txt',''),'gesammtngrid');  
%                 %und nun alle zusammen achtung schaltjahr,               
%                 

                jahr=str2num(verz(i).name(findstr((strrep(verz(i).name,'.txt','')),'200'):findstr((strrep(verz(i).name,'.txt','')),'200')+3))
                 alles(jahr-1999,:,:,1:365)=newngrid(:,:,1:365);
                
            end
             save (strcat('JahreCAMIChum',strrep(verz(i).name,'.txt','')),'alles');
        end     
    
        
           
        
             
   case 'reg_nest'
        load Nesterov
        for lat=1:size(Nestv,2)
            for lon=1:size(Nestv,3)
                if ~isnan(Nestv(1,lat,lon,1))
                    [RHO,PVAL]=corrcoef(reshape(Nestv(:,lat,lon,:),365*7,1),reshape(Nestk(:,lat,lon,:),365*7,1));
                    Reg.R(lat,lon)=RHO(2,1);
                    Reg.a(lat,lon)=regress(reshape(Nestk(:,lat,lon,:),365*7,1),reshape(Nestv(:,lat,lon,:),365*7,1));           
                end
            end
        end
        save reg_nest
    case 'read_hdf_new'                
        firevalues=[7,8]
        file=varargin{2};
        if nargin==3
            unix=1;
            slash='/';
        else
            unix=0;
            slash='\';
        end
        allnr=0;
        all_files{1}=[];
        zipnr=0;
        zip_files{1}=[];
        
        if isempty(strfind(file,'.hdf')) &  isempty(strfind(file,'.zip'))% dann ist es ein Verzeichniss
            direc=file;
            direczips=direc;
            if unix==0
                if direc(size(direc,2))~='\';
                    direc(size(direc,2)+1)='\';
                end
            else
              if direc(size(direc,2))~='/';
                direc(size(direc,2)+1)='/';                
              end
            end
          verz=dir(file);
            for i=1:size(verz,1)
                if ~isempty(strfind(verz(i).name,'.hdf'))
                    allnr=allnr+1;
                    all_files{allnr}=verz(i).name;
                end
            end
            for i=1:size(verz,1)
                if ~isempty(strfind(verz(i).name,'.zip'))
                    zipnr=zipnr+1;
                    zip_files{zipnr}=verz(i).name;
                    
                end
            end            
        elseif ~isempty(strfind(file,'.zip'))
            zip_files{1}=file;
            zip_nr=1;
        elseif ~isempty(strfind(file,'.hdf'))
            all_files{1}=file;
            direc='';
        else
            'keine files zur bearbeitung gefunden'
            return
        end
        if zipnr>0
            load MODISFIRE
            load ('landuses','use');
            for zipnr=1:size(zip_files,2)
                zipdirstr=strcat(direczips,slash,zip_files{zipnr});
                if unix==1
                    zipdirstr
                    direczips
                    eval (['! unzip ', zipdirstr,' -x *.xml *h22v05* *h23v05* *h22h06* *h23v06* *h16v09* *h17v09* *h23v09* *h23v10* *h16v10* *h17v10* *h18v10* *h16v11* *h17v11* *h18v11* *h16v12* *h23v11* *h17v12* *h18v12* *h21v12* *h22v12* *h23v12* ' ]);                      
                    % downscale ('read_hdf',strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')),'unix');
                    % zur Beschleunigung steht der code hier nocheinmal....                    
                    verz=dir(strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')));
                    direc=strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip',''),slash);
                    for i=1:size(verz,1)
                        if ~isempty(strfind(verz(i).name,'.hdf'))
                            allnr=allnr+1;
                            all_files{allnr}=verz(i).name;
                        end
                    end
                    for allnr=1:size(all_files,2)
                        all_files{allnr};
                        % mal schauen ob wir das file schon hatten
                        filefound=0;
                        if ~isempty(readfiles(1).filelist)
                            for i=1:size (readfiles,2)
                                for ii=1:size (readfiles(i).filelist,2)
                                    filefound=max(strcmp (readfiles(i).filelist{ii},all_files{allnr}),filefound);                                    
                                end
                            end
                        end

                        if filefound==0                    %                    ersteinmal das Datum finden zum eintragen.                            
                            if unix==1
                                ord=strrep(strcat(direc,all_files{allnr}),'\','/');
                            else
                                ord=strrep(strcat(direc,all_files{allnr}),'/','\');
                            end
                            ord
                            fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','most confident detected fire');     
                            if isempty (fire)
                                fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','FireMask');     
                            end
                                
                            [il,is]=find(fire==8 | fire==7 | fire==9); % look for fires
                            
                            %und die info
                            info= hdfinfo(strcat(direc,all_files{allnr}));
                            strinfo=strrep(info.Attributes(2).Value,'(','');
                            strinfo=strrep(strinfo,')','');
                            upperstart=findstr(strinfo,'UpperLeftPointMtrs=');
                            upperend=findstr(strinfo,'		LowerRightMtrs=');
                            lowerend=findstr(strinfo,'		Projection');
                            projstart=findstr(strinfo,'ProjParams=')+size('ProjParams=',2);
                            projend=findstr(strinfo,',0,0,0,0,0,0,0,0,0,0,0,0')-1;            
                            UL=str2num(strinfo(upperstart+size('UpperLeftPointMtrs=',2):upperend-1));
                            LR=str2num(strinfo(upperend+size('		LowerRightMtrs=',2):lowerend-1));            
                            Proj=str2num(strinfo(projstart:projend));
                            datstr=strrep(info.Attributes(4).Value,'-','');
                            daystra=findstr(datstr,'DAYSOFYEAR');            
                            daystrd=findstr(datstr(daystra(1):daystra(2)),'"');
                            date=str2num(datstr(daystra(1)+daystrd(1):daystra(1)+daystrd(2)-2))             ;
                            %finde das richtige datum
                            h=str2num(all_files{allnr}(findstr(all_files{allnr},'h')+1:findstr(all_files{allnr},'h')+2));
                            v=str2num(all_files{allnr}(findstr(all_files{allnr},'v')+1:findstr(all_files{allnr},'v')+2));
                            datfound=0;
                            if isempty(readfiles(1).datum)                                            
                                readfiles(1).datum{1}=date;
                                readfiles(1).filelist{1}=all_files{allnr};
                                readfiles(1).tiles{1}=zeros(8)-1;;
                                readfiles(1).tiles{1}(h-15,v-4)=size(il,1);
                            else
                                for i=1:size (readfiles,2)
                                    if (readfiles(i).datum{1}==date)
                                        readfiles(i).filelist{size(readfiles(i).filelist,2)+1}=all_files{allnr};
                                        readfiles(i).tiles{1}(h-15,v-4)=size(il,1);
                                        datfound=1;                        
                                    end
                                end
                                if datfound==0
                                    readfiles(size(readfiles,2)+1).datum{1}=date;
                                    readfiles(size(readfiles,2)).filelist{1}=all_files{allnr}; 
                                    readfiles(size(readfiles,2)).tiles{1}=zeros(8)-1;                                    
                                    readfiles(size(readfiles,2)).tiles{1}(h-15,v-4)=size(il,1);
                                end
                            end


                            if ~isempty(il)                                
                                %find all fires
                                XDIM=1200;
                                %calculate lat und long for them
                                qual=fire(find(fire==7 | fire==8 | fire==9));
                                x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1);
                                y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2);
                                lat=360*(y./(Proj*2*pi));
                                lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)));
                                xuse=round((lon+28.8371)/0.00892857);
                                yuse=round((lat+36.0246)/0.00892857);
                                if ~isempty (firelist)
                                    oldsize=size(firelist,1);         
                                else
                                    oldsize=0;
                                end
                                uses=0;
%                                 for i=1:size(lon,1)
%                                     uses(i)=use(9187-round((lat(i)+36.0246)/0.00892857),round((lon(i)+28.8371)/0.00892857));
%                                 end
                                ladosave (strcat('MODUSE_H',num2str(h),'V',num2str(v)),'modisuse');
                                firelist(oldsize+1:oldsize+size(lat,1),1)=lat;
                                firelist(oldsize+1:oldsize+size(lat,1),2)=lon;
                                firelist(oldsize+1:oldsize+size(lat,1),3)=date;
                                firelist(oldsize+1:oldsize+size(lat,1),4)=qual;
                                firelist(oldsize+1:oldsize+size(lat,1),5)=uses;
                                strcat ('found_ ',num2str(size(lat,1)),'_fires at_',num2str(date), '_in_',strcat(direc,all_files{allnr})) 
                            end
                            %hier wird getested ob die gespeicherten Werte zu gross werden.
                            save ('MODISFIRE','firelist','readfiles');
                            if prod(size(firelist))+prod(size(firelist))>30000000 % das ist der Windowswert
                                save (strcat('MODISFIRELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'firelist');
                                save (strcat('MODISFLELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'readfiles');
                                save (strcat('allessicher',strrep(strrep(num2str(clock),' ',''),'.','')));                                
                                firelist=[];
                                save ('MODISFIRE','firelist','readfiles');                                          
                            end
                        end
                    end % das file hatten wir schon mal
                    
                else  % Windows                  
                    unzip(strcat(direc,zip_files{zipnr}));   
                    cd (strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')));                  
                    del ('*.xml');
                    delarray=[                    16,5; 
                        21,5; 
                        22,5;
                        23,5;                   
                        22,6;
                        23,6;
                        16,9;
                        17,9;
                        23,9;
                        23,10;
                        16,10;
                        17,10;
                        18,10;
                        16,11;
                        17,11;
                        18,11;
                        16,12;
                        23,11;
                        17,12;
                        18,12;
                        21,12;                    
                        22,12;
                        23,12;
                        ];
                    
                    for i=1:size (delarray,1)
                        if delarray(i,2)<10                                           
                            delete (strcat('*h',num2str(delarray(i,1)),'v0',num2str(delarray(i,2)),'*'));
                        else
                            delete (strcat('*h',num2str(delarray(i,1)),'v',num2str(delarray(i,2)),'*'));
                        end
                    end
                    cd ..
                    cd ..                
                    %achtung ich werrde jetzt recursiv!
                    downscale ('read_hdf',strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')));            
                end


                rmdir('PullDir','s')
            end
        end

        rekursiv=0;
        if unix==0 & ~isempty(all_files{1}) % weil windows is t noch rekursiv
            load MODISFIRE
            load ('landuses','use');
             for allnr=1:size(all_files,2)
                all_files{allnr};
                % mal schauen ob wir das file schon hatten
                filefound=0;
                if ~isempty(readfiles(1).filelist)
                    for i=1:size (readfiles,2)
                        for ii=1:size (readfiles(i).filelist,2)
                            filefound=max(strcmp (readfiles(i).filelist{ii},all_files{allnr}),filefound);                                    
                        end
                    end
                end
                if filefound==0
                    %                    ersteinmal das Datum finden zum eintragen.
                    
                    if unix==1
                        ord=strrep(strcat(direc,all_files{allnr}),'\','/');
                    else
                        ord=strrep(strcat(direc,all_files{allnr}),'/','\');
                    end
                    ord 
                    fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','most confident detected fire');                    
                    [il,is]=find(fire==8 | fire==7 | fire==9); % look for fires
                    
                    %und die info
                    info= hdfinfo(strcat(direc,all_files{allnr}));
                    strinfo=strrep(info.Attributes(2).Value,'(','');
                    strinfo=strrep(strinfo,')','');
                    upperstart=findstr(strinfo,'UpperLeftPointMtrs=');
                    upperend=findstr(strinfo,'		LowerRightMtrs=');
                    lowerend=findstr(strinfo,'		Projection');
                    projstart=findstr(strinfo,'ProjParams=')+size('ProjParams=',2);
                    projend=findstr(strinfo,',0,0,0,0,0,0,0,0,0,0,0,0')-1;            
                    UL=str2num(strinfo(upperstart+size('UpperLeftPointMtrs=',2):upperend-1));
                    LR=str2num(strinfo(upperend+size('		LowerRightMtrs=',2):lowerend-1));            
                    Proj=str2num(strinfo(projstart:projend));
                    datstr=strrep(info.Attributes(4).Value,'-','');
                    daystra=findstr(datstr,'DAYSOFYEAR');            
                    daystrd=findstr(datstr(daystra(1):daystra(2)),'"');
                    date=str2num(datstr(daystra(1)+daystrd(1):daystra(1)+daystrd(2)-2))             ;
                    %finde das richtige datum
                    h=str2num(all_files{allnr}(findstr(all_files{allnr},'h')+1:findstr(all_files{allnr},'h')+2));
                    v=str2num(all_files{allnr}(findstr(all_files{allnr},'v')+1:findstr(all_files{allnr},'v')+2));
                    datfound=0;
                    if isempty(readfiles(1).datum)                                            
                        readfiles(1).datum{1}=date;
                        readfiles(1).filelist{1}=all_files{allnr};
                        readfiles(1).tiles{1}=zeros(8)-1;;
                        readfiles(1).tiles{1}(h-15,v-4)=size(il,1);
                    else
                        for i=1:size (readfiles,2)
                            if (readfiles(i).datum{1}==date)
                                readfiles(i).filelist{size(readfiles(i).filelist,2)+1}=all_files{allnr};
                                readfiles(i).tiles{1}(h-15,v-4)=size(il,1);
                                datfound=1;                        
                            end
                        end
                        if datfound==0
                            readfiles(size(readfiles,2)+1).datum{1}=date;
                            readfiles(size(readfiles,2)).filelist{1}=all_files{allnr};   
                            readfiles(size(readfiles,2)).tiles{1}(h-15,v-4)=size(il,1);
                        end
                    end
                                      
                    
                    if ~isempty(il)
                        
                        %find all fires
                        XDIM=1200;
                        %calculate lat und long for them
                        [il,is]=find(fire==7 | fire==8 | fire==9);
                        qual=fire(find(fire==7 | fire==8 | fire==9));
                        x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1);
                        y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2);
                        lat=360*(y./(Proj*2*pi));
                        lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)));
                        xuse=round((lon+28.8371)/0.00892857);
                        yuse=round((lat+36.0246)/0.00892857);
                        if ~isempty (firelist)
                            oldsize=size(firelist,1);         
                        else
                            oldsize=0;
                        end
                        uses=0;
                        si_1=size(use,1);
                        si_2=size(use,2);
                        
                        for i=1:size(lon,1)
                            if (9187-round((lat(i)+36.0246)/0.00892857)) <si_1 & round((lon(i)+28.8371)/0.00892857)<si_2
                                uses(i)=use(9187-round((lat(i)+36.0246)/0.00892857),round((lon(i)+28.8371)/0.00892857));
                            end
                        end
                        firelist(oldsize+1:oldsize+size(lat,1),1)=lat;
                        firelist(oldsize+1:oldsize+size(lat,1),2)=lon;
                        firelist(oldsize+1:oldsize+size(lat,1),3)=date;
                        firelist(oldsize+1:oldsize+size(lat,1),4)=qual;
                        firelist(oldsize+1:oldsize+size(lat,1),5)=uses;
                        strcat ('found_ ',num2str(size(lat,1)),'_fires at_',num2str(date), '_in_',strcat(direc,all_files{allnr})) 
                    end
                    %hier wird getested ob die gespeicherten Werte zu gross werden.
                    save ('MODISFIRE','firelist','readfiles');
                    if prod(size(firelist))+prod(size(firelist))>30000000 % das ist der Windowswert
                        save (strcat('MODISFIRELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'firelist');
                        save (strcat('MODISFLELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'readfiles');
                        firelist=[];
                        save ('MODISFIRE','firelist','readfiles');                                          
                    end
                end
            end % das file hatten wir schon mal
                %            figure(4);
%            scatter(lon,lat);
%            % This part displayes tile and land use
%             is=[0,1199];
%             il=[0,1199];
%             x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1)
%             y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2)
%             lat=360*(y./(Proj*2*pi))
%             lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)))
%             figure(1)
%             pcolor(double((fire)));
%             shading flat
%             clear fire;           
%             load ('landuses','use');
%             xuse=round((lon+28.8371)/0.00892857) % das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
%             yuse=round((lat+36.0246)/0.00892857)
%             clear fire;
% %             size(double(use(xuse(1):use(xuse(2),yuse(2):yuse(1)))))
%             figure(2)
%             pcolor(double(use(yuse(2):yuse(1),xuse(1):xuse(2))));
%             shading flat
            
        end % for allfiles
        
    
    case 'Landsea'
        vtemp=1;
             for lati=-37.5:5:32.5 % bins gehen nachher bis 37.5 
                 tot(lati/5+8.5,24)=0;
             end
        modisuse=0;
        counter=1;
        % generating an own land sea mask
        % a full set of files has to be in the directory to be read
        file=varargin{2};
        if nargin==3
            unix=1;
            slash='/';
        else
            unix=0;
            slash='\';
        end
        allnr=0;
        all_files{1}=[];
        zipnr=0;
        zip_files{1}=[];
        
        if isempty(strfind(file,'.hdf')) &  isempty(strfind(file,'.zip'))% dann ist es ein Verzeichniss
            direc=file;
            if unix==0
                if direc(size(direc,2))~='\';
                    direc(size(direc,2)+1)='\';
                end
            else
                if direc(size(direc,2))~='/';
                    direc(size(direc,2)+1)='/';                
                end
            end
            verz=dir(file);
            for i=1:size(verz,1)
                if ~isempty(strfind(verz(i).name,'.hdf'))
                    allnr=allnr+1;
                    all_files{allnr}=verz(i).name;
                end
            end
        elseif ~isempty(strfind(file,'.hdf'))
            all_files{1}=file;
            direc='';
        else
            'keine files zur bearbeitung gefunden'
            return
        end
        load LANDSEA
        
        load use;
        for allnr=1:size(all_files,2)
            all_files{allnr};
            % mal schauen ob wir das file schon hatten
            filefound=0;
            if filefound==0                    %                    ersteinmal das Datum finden zum eintragen.
                if unix==1
                    ord=strrep(strcat(direc,all_files{allnr}),'\','/');
                else
                    ord=strrep(strcat(direc,all_files{allnr}),'/','\');
                end
                ord
                fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','most confident detected fire');     
                if isempty (fire)
                    fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','FireMask');                                     
                end
                horz=str2num(ord(19:21));
                vert=str2num(ord(22:23));
                
                [il,is]=find(fire>-1);%4); % look for fires
                
                %und die info
                info= hdfinfo(strcat(direc,all_files{allnr}));
                strinfo=strrep(info.Attributes(2).Value,'(','');
                strinfo=strrep(strinfo,')','');
                upperstart=findstr(strinfo,'UpperLeftPointMtrs=');
                upperend=findstr(strinfo,'		LowerRightMtrs=');
                lowerend=findstr(strinfo,'		Projection');
                projstart=findstr(strinfo,'ProjParams=')+size('ProjParams=',2);
                projend=findstr(strinfo,',0,0,0,0,0,0,0,0,0,0,0,0')-1;            
                UL=str2num(strinfo(upperstart+size('UpperLeftPointMtrs=',2):upperend-1));
                LR=str2num(strinfo(upperend+size('		LowerRightMtrs=',2):lowerend-1));            
                Proj=str2num(strinfo(projstart:projend));
                datstr=strrep(info.Attributes(4).Value,'-','');
                daystra=findstr(datstr,'DAYSOFYEAR');            
                daystrd=findstr(datstr(daystra(1):daystra(2)),'"');
                date=str2num(datstr(daystra(1)+daystrd(1):daystra(1)+daystrd(2)-2))             ;
                %finde das richtige datum
                h=str2num(all_files{allnr}(findstr(all_files{allnr},'h')+1:findstr(all_files{allnr},'h')+2));
                v=str2num(all_files{allnr}(findstr(all_files{allnr},'v')+1:findstr(all_files{allnr},'v')+2));
%                 if v==11 & h==19%(v~=vtemp)
%                     %vtemp=v;
%                     'break'
%                 end
                datfound=0;
                if isempty(readfiles(1).datum)                                            
                    readfiles(1).datum{1}=date;
                    readfiles(1).filelist{1}=all_files{allnr};
                    readfiles(1).tiles{1}=zeros(8)-1;;
                    readfiles(1).tiles{1}(h-15,v-4)=size(il,1);
                else
                    for i=1:size (readfiles,2)
                        if (readfiles(i).datum{1}==date)
                            readfiles(i).filelist{size(readfiles(i).filelist,2)+1}=all_files{allnr};
                            readfiles(i).tiles{1}(h-15,v-4)=size(il,1);
                            datfound=1;                        
                        end
                    end
                    if datfound==0
                        readfiles(size(readfiles,2)+1).datum{1}=date;
                        readfiles(size(readfiles,2)).filelist{1}=all_files{allnr}; 
                        readfiles(size(readfiles,2)).tiles{1}=zeros(8)-1;                                    
                        readfiles(size(readfiles,2)).tiles{1}(h-15,v-4)=size(il,1);
                    end
                end


                if ~isempty(il)
                    XDIM=1200;
                    %calculate lat und long for them
                    %                                [il,is]=find(fire<4);% for the land sea mask
                    pos(counter).LR=LR;
                    pos(counter).UL=UL;
                    pos(counter).h=h;
                    pos(counter).v=v;                   
%                     x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1);
%                     y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2);
%                     lat=360*(y./(Proj*2*pi));
%                     lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)));
                    lat=360*((((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2))./(Proj*2*pi));    %  Eigentlich +0.5 aber dei Zaehlung f�ngt mit null an 
                    lon=360*((((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1))./(cos(lat/180*pi)*(Proj*2*pi)));  % siehe oben
                    pos(counter).lat= 360*((((1+0.5).*((LR(2)-UL(2))/XDIM))+UL(2))./(Proj*2*pi));
                    pos(counter).lon=360*((((1+0.5).*((LR(1)-UL(1))/XDIM))+UL(1))./(cos(pos(counter).lat/180*pi)*(Proj*2*pi)));
                    counter=counter+1
                    xuse=round((lon+28.8371)/0.00892857);  
                    yuse=9187-round((lat+36.0246)/0.00892857);
                    %finde alle die zu gros sind        
%                     [zu_gros]=find (xuse>9717);
%                     xuse(zu_gros)=[];
%                     yuse(zu_gros)=[];
%                     lat(zu_gros)=[];
%                     lon(zu_gros)=[];
%                     [zu_gros]=find (yuse>9187);
%                     xuse(zu_gros)=[];
%                     yuse(zu_gros)=[];
%                     lat(zu_gros)=[];
%                     lon(zu_gros)=[];
                    if size(use,1)<max(max(xuse),max(yuse))
                        use(size(use,1):max(max(xuse),max(yuse)),size(use,1):max(max(xuse),max(yuse)))=uint8(0);
                        save ('use','use');
                    end
                    sei=size(use,1);
                    uses=uint8(use(yuse+(sei*(xuse-1))))                     ;                         
                    %modisuse((v-5)*1200+1:(v-4)*1200,(h-16)*1200+1:(h-15)*1200)=uint8(reshape (uses,1200,1200));
                    modisuse=uint8(reshape (uses,1200,1200));
                    Modisuse((v-5)*1200+1:(v-4)*1200,(h-16)*1200+1:(h-15)*1200)=modisuse;
                  
%                     for i=1:24 
%                         for lati=-37.5:5:37.5
%                             lati/5+8.5,i
%                             tot(lati/5+8.5,i)=sum((lat>=lati & lat<lati+5 & uses==i),1)+tot(lati/5+8.5,i);
%                         end
%                     end

                      tottemp=hist3([lat+90 uses],'Edges',{90-37.5:5:90+37.5 0.5:1:24.5}); 
                      % achtung BUG hist3 kann nicht mit negativen Zhalen
                      % rechnen.... deshalb immer plus90
                      %die Werte die auf dem Rand des letzten bins liegen werden in einen weiteren bin reingeschrieben ... l�schen:
                      tot=tottemp(1:15,1:24)+tot;
%             figure(2)
%             pcolor(double(use(yuse(2):yuse(1),xuse(1):xuse(2))));
%                     figure,imshow((fire),[])
%                     %figure,imshow(modisuse,[])
%                     figure,imshow((use(min(yuse):max(yuse),min(xuse):max(xuse))),[]);
%                    save (strcat('MODUSE_H',num2str(h),'V',num2str(v)));
                    strcat ('found_ ',num2str(size(lat,1)),'_fires at_',num2str(date), '_in_',strcat(direc,all_files{allnr})) 
                    save ('Modisuse','Modisuse','tot');
                end
                %hier wird getested ob die gespeicherten Werte zu gross werden.
%                 if  mod(counter,10)==0 
%                     save ('LANDSEA','modisuse','readfiles','pos');
%                 end
            end
        end % das file hatten wir schon mal
%        save ('LANDSEA','modisuse','readfiles','pos');
       
        figure
        bar3(tot)
        
    
        
        
        
        
       
        
   case 'MODIS_plot_over_time_unix_new'
       load  ('Modisuse','tot');
       months=0;
       abs=8;
       load ('fireonly');
       for time=20000100:100:20061200
           if mod(time,10000)<=1200 & mod(time,10000)>0 
               months=months+1;
               time
               firelisttemp=firelist(firelist(:,3)>=time & firelist(:,3)<time+100 ,[1 5]);
               if size(firelisttemp,1)>0
                   plotvaluetemp=hist3(firelisttemp,'Edges',{-37.5:5:37.5 1:24}); 
                   plotvalue(:,:,months)=plotvaluetemp(:,:);                           
               end
           end
       end
       plotvalue(16,:,:)=[];
       plotvalue_y=zeros(15,25,12);
       for ii=1:24 % without cities            
           for i=1:size(plotvalue,3)
               for lati=1:size(tot,1)
                   if tot(lati,ii)>100
                       plotvalue_y(lati,ii,mod(i-1,12)+1)=plotvalue_y(lati,ii,mod(i-1,12)+1)+plotvalue(lati,ii,i)./tot(lati,ii);
                   else
                       plotvalue_y(lati,ii,mod(i-1,12)+1)=NaN;
                   end
               end
           end
       end
        save ('plotvaluetemp','plotvalue')
        figure
        surf(squeeze(plotvalue_y(:,9,:)));
        shading interp;
        figure
        surf(squeeze(plotvalue_y(:,11,:)));
        shading interp;
        le={'Closed evergreen lowland forest';
            'Degraded evergreen lowland forest';
            'Submontane forest (900 -1500 m)';
            'Montane forest (>1500 m)';
            'Swamp forest';
            'Mangrove';
            'Mosaic Forest / Croplands';
            'Mosaic Forest / Savanna';
            'Closed deciduous forest';
            'Deciduous woodland';
            'Deciduous shrubland with sparse trees';
            'Open deciduous shrubland';
            'Closed grassland';
            'Open grassland with sparse shrubs';
            'Open grassland';
            'Sparse grassland';
            'Swamp bushland and grassland';
            'Croplands (>50%)';
            'Croplands with open woody vegetation';
            'Irrigated croplands';
            'Tree crops';
            'Sandy desert and dunes';
            'Stony desert';
            'Bare rock';            
            'Salt hardpans';
            'Waterbodies';
            'Cities';            
            }; 
        save ('plotvaluenew')
        figure,pcolor(squeeze(plotvalue(:,18,:)));
    %    shading flat;
    figure, hold on, 
        
        
        for i=1:24 
            subplot(4,6,i)
            surf(squeeze(plotvalue_y(:,i,:)));
            axis([1,12, 1,15 0 0.5])
            
            shading interp
            title(le{i})
            set(gca,'YTick',[2 8 14]);
            set(gca,'XTick',[1 7 12]);
            set(gca,'XTickLabel',{'Jan','Jul','Dec'})
            set(gca,'YTickLabel',{'35 S','Aqu','35 N'})
           
        end
        
        plotvalue_yz=zeros(8,24,6);
        plotvalue_yt=plotvalue_y;
        plotvalue_yt(isnan(plotvalue_y))=0;
        
        for ii=1:24 % without desert & cities            
            for month=1:12
                i=month
                lati=8 %Aquator 
                if month<7
                    plotvalue_yz(9-lati,ii,i)=(plotvalue_yt(lati,ii,i+6)+plotvalue_yt(lati,ii,i));
                else
                    plotvalue_yz(9-lati,ii,i)=(plotvalue_yt(lati,ii,i-6)+plotvalue_yt(lati,ii,i));
                end
                for lati=1:7
                   if tot(lati,ii)+ tot(16-lati,ii)>100 & lati~=8                     
                       if month<7
                           plotvalue_yz(9-lati,ii,i)=(((plotvalue_yt(lati,ii,i)*tot(lati,ii))+plotvalue_yt(16-lati,ii,i+6)*tot(16-lati,ii))./(tot(lati,ii)+ tot(16-lati,ii)));
                       else
                           plotvalue_yz(9-lati,ii,i)=(((plotvalue_yt(lati,ii,i)*tot(lati,ii))+plotvalue_yt(16-lati,ii,i-6)*tot(16-lati,ii))./(tot(lati,ii)+ tot(16-lati,ii)));
                           %                         plotvalue_yz(lati,ii,i-6)=plotvalue_yt(lati,ii,i-6)./(tot(lati,ii)+ tot(15-lati,ii));
                       
                       end
                   else
                        plotvalue_yz(9-lati,ii,i)=NaN;
                   end                
                end                
            end
        end
        figure,surf(squeeze(plotvalue_yz(:,10,:))),shading interp;   
        figure,surf(squeeze(plotvalue_yz(:,11,:)));
      shading interp;
        plotvalue_yz=plotvalue_yz/7;
        figure, hold on, 
        for i=1:24 
            subplot(4,6,i)
            surf(squeeze(plotvalue_yz(:,i,:)));
            axis([1,12, 1,8, 0, 0.05])
            
            shading interp
            title(le{i})
                        set(gca,'YTick',[1 5 8]);
                        set(gca,'XTick',[1 7 12]);
                        set(gca,'ZTick',[0 0.05]);
                        set(gca,'XTickLabel',{'Jan','Jul','Dec'})
                        set(gca,'YTickLabel',{'Eq ','25 deg','40 deg'})
                        set(gca,'ZTickLabel',{'0 ','0.5'})
                        
%             i=0
%             i=i+1
%             [testpara_1 testpara_2]=find(ones(size(squeeze(plotvalue_yz(:,i,:)))));  %8 Streifen a 12 Monate
%             testdata=squeeze(plotvalue_yz(:,i,:));
%             testdatar=reshape(squeeze(plotvalue_yz(:,i,:)),[prod(size(squeeze(plotvalue_yz(:,i,:)))) 1]);
%             b=glmfit([testpara_1 testpara_2 (testpara_1).^20 (testpara_2).^20], [testdatar*1000 ones(size(testdatar))*1000], 'binomial','logit' );
%             yfit=glmval(b,[testpara_1 testpara_2 (testpara_1).^20 (testpara_2).^20], 'logit' );
%             fitdata=reshape(yfit,size(testdata));
%             figure,surf(fitdata),shading interp,   title(le{i}) 
%             figure,surf(testdata),shading interp,   title(le{i})
%        
        end
          plotvaluesave=round(plotvalue_yz*12/7*1000);
          plotvaluesave(isnan(plotvaluesave))=0;
          [testpara_1 testpara_2]=find(ones(size(squeeze(plotvalue_yz(:,:,1)))));  %8 Streifen a 24 uses%             
          fid=fopen('Fire_frequencies_prom.txt','w');
          for i=1:prod(size(squeeze(plotvalue_yz(:,:,1))))
              dist=testpara_1(i);
              use=testpara_2(i);
              fprintf (fid,strcat(num2str([ dist use squeeze(plotvaluesave(dist,use,:))']),'\n'));
          end
          fclose( fid)
     
          save plotvalues
        
        
        
        
        
        
        
        
    case 'MODIS_plot_over_time_unix'
          
        load  ('Modisuse','tot');        
        figure
        bar3(tot);
        load ('fireonlynew');
        firelist(:,3)=mod(fix(firelist(:,3)/100),100);
        firelist(:,1)=fix(firelist(:,1)/5+8.5);
        totNaN=tot;
        totNaN(tot<100)=NaN;
        for i=1:24 % without desert & cities
            i
            plotvaluetemp=firelist(firelist(:,5)==i,[1,3]);  % eins ist lat, 3 ist datum
            plotvalue(i,:,:)=hist3(plotvaluetemp,{ 1:15 1:12});
            %             for time=1:12
%                 %                firelist=firelistall(firelistall(:,5)==i,:);   
%                 for lat=1:16
%                     %                        if tot(lat/5+8,i)>100
%                     %                            plotvalue(lat/5+8,i,months)=size(firelist( firelist(:,3)>=time  & firelist(:,3)<time+100 & firelist (:,1)>=lat & firelist(:,1)<lat+5  ,: ),1);
%                     plotvalue(lat,i,time)=size(firelist(firelist(:,5)==i  & firelist(:,3)==time & firelist(:,1)==lat,: ),1);
%                     %plotvalue(lat/5+8,i,months)=size(find (firelist (:,1)>=lat & firelist(:,1)<lat+5 & firelist(:,5)==i  & firelist(:,3)>=time & firelist(:,3)<time+100 ),1)/tot(lat/5+8,i);
%                     %plotvalue2(lat/5+8,i,months)=size(find (fireout2(:,2)>lat & fireout2(:,2)<lat+5 & fireout2(:,4)==i  & fireout2(:,1)>=time & fireout2(:,1)<time+100 ),1)/tot(lat/5+8,i);
%                     %                        else
%                     %plotvalue(lat,i,time)=0;
%                     %                                plotvalue2(lat/5+8,i,months)=0;
%                     %                       end
%                 end
%             end            
        end
        save ('plotvalues11','plotvalue')
%         plotvalue_y=zeros(15,25,12);
%         for ii=1:24 % without desert & cities            
%             for i=1:92
%                 for lati=1:size(tot,1)
%                    if tot(lati,ii)>0
%                         plotvalue_y(lati,ii,mod(i+10,12)+1)=plotvalue_y(lati,ii,mod(i+10,12)+1)+plotvalue(lati,ii,i)./tot(lati,ii);
%                    else
%                         plotvalue_y(lati,ii,mod(i+10,12)+1)=NaN;
%                    end                
%                 end                
%             end
%         end
       for time=1:12
          plotvalue_y(:,:,time)=squeeze(plotvalue(:,:,time))'./totNaN;
       end
        le={'Closed evergreen lowland forest';
            'Degraded evergreen lowland forest';
            'Submontane forest (900 -1500 m)';
            'Montane forest (>1500 m)';
            'Swamp forest';
            'Mangrove';
            'Mosaic Forest / Croplands';
            'Mosaic Forest / Savanna';
            'Closed deciduous forest';
            'Deciduous woodland';
            'Deciduous shrubland with sparse trees';
            'Open deciduous shrubland';
            'Closed grassland';
            'Open grassland with sparse shrubs';
            'Open grassland';
            'Sparse grassland';
            'Swamp bushland and grassland';
            'Croplands (>50%)';
            'Croplands with open woody vegetation';
            'Irrigated croplands';
            'Tree crops'
            'Sandy desert and dunes';
            'Stony desert';
            'Bare rock';            
            'Salt hardpans';
            'Waterbodies';
            'Cities';            
            }; 
      %  save ('plotvalue')
%        plotvalue_y(15,1,8)=0;
        figure, hold on, 
        for i=1:24 
            subplot(4,6,i)
            surf(squeeze(plotvalue_y(:,i,:)));
            axis([1,12, 1,15 0 0.5])
            
            shading interp
            title(le{i})
            set(gca,'YTick',[2 8 14]);
            set(gca,'XTick',[1 7 12]);
            set(gca,'XTickLabel',{'Jan','Jul','Dec'})
            set(gca,'YTickLabel',{'35 S','Aqu','35 N'})
           
        end
        plotvalue_yz=zeros(7,25,6);
        plotvalue_yt=plotvalue_y;
        plotvalue_yt(isnan(plotvalue_y))=0;
        
        for ii=1:24 % without desert & cities            
            for i=2:7
                for lati=1:7
                   if tot(lati,ii)+ tot(15-lati,ii)>100 
                     
                       if i<7
                           plotvalue_yz(lati,ii,i-1)=(((plotvalue_yt(lati,ii,i+6)*tot(lati,ii))+plotvalue_yt(15-lati,ii,i)*tot(15-lati,ii))./(tot(lati,ii)+ tot(15-lati,ii)));
                       else
                           plotvalue_yz(lati,ii,i-1)=(((plotvalue_yt(lati,ii,i-6)*tot(lati,ii))+plotvalue_yt(15-lati,ii,i)*tot(15-lati,ii))./(tot(lati,ii)+ tot(15-lati,ii)));
                           %                         plotvalue_yz(lati,ii,i-6)=plotvalue_yt(lati,ii,i-6)./(tot(lati,ii)+ tot(15-lati,ii));
                       end
                   else
                        plotvalue_yz(lati,ii,i-1)=NaN;
                   end                
                end                
            end
        end
        figure,surf(squeeze(plotvalue_yz(:,10,:))),shading interp;
        figure, hold on, 
        for i=1:24 
            subplot(4,6,i)
            surf(squeeze(plotvalue_yz(:,i,:)));
            axis([1,7, 1,6, 0, 0.2])
            
            shading interp
            title(le{i})
%             set(gca,'YTick',[2 8 14]);
%             set(gca,'XTick',[1 7 12]);
%             set(gca,'XTickLabel',{'Jan','Jul','Dec'})
%             set(gca,'YTickLabel',{'35 S','Aqu','35 N'})
           
        end
    
     save ('plotvalues')        ;

        
    case 'MODIS_plot_over_nest_unix'
        load ('firelistnest','firelistnest')  
        load  ('Modisuse','tot');
        months=0;
        load ('fireonly');
        firelist(:,3)=firelistnest;
        clear firelistnest
        deltanest=0
        maxnest=0
        for nest=0:deltanest:maxnest
                for i=1:24 % without desert & cities
                    %                firelist=firelistall(firelistall(:,5)==i,:);   
                    for lat=-35:5:35
                        if tot(lat/5+8,i)>100
                            plotvalue(lat/5+8,i,months)=size(firelist(firelist(:,5)==i  & firelist(:,3)>=nest & firelist(:,3)<nest+deltanest & firelist (:,1)>=lat & firelist(:,1)<lat+5  ,: ),1);
                        else
                            plotvalue(lat/5+8,i,months)=0;
                        end
                end
            end
        end
        save ('plotvalues11')
        plotvalue_y=zeros(15,25,12);
        for ii=1:24 % without desert & cities            
            for i=1:92
                for lati=1:size(tot,1)
                   if tot(lati,ii)>0
                        plotvalue_y(lati,ii,mod(i+10,12)+1)=plotvalue_y(lati,ii,mod(i+10,12)+1)+plotvalue(lati,ii,i)./tot(lati,ii);
                   else
                        plotvalue_y(lati,ii,mod(i+10,12)+1)=NaN;
                   end                
                end                
            end
        end
  
        figure
        surf(squeeze(plotvalue(:,11,:)));
        shading interp;
  le={'Closed evergreen lowland forest';
            'Degraded evergreen lowland forest';
            'Submontane forest (900 -1500 m)';
            'Montane forest (>1500 m)';
            'Swamp forest';
            'Mangrove';
            'Mosaic Forest / Croplands';
            'Mosaic Forest / Savanna';
            'Closed deciduous forest';
            'Deciduous woodland';
            'Deciduous shrubland with sparse trees';
            'Open deciduous shrubland';
            'Closed grassland';
            'Open grassland with sparse shrubs';
            'Open grassland';
            'Sparse grassland';
            'Swamp bushland and grassland';
            'Croplands (>50%)';
            'Croplands with open woody vegetation';
            'Irrigated croplands';
            'Tree crops'
            'Sandy desert and dunes';
            'Stony desert';
            'Bare rock';            
            'Salt hardpans';
            'Waterbodies';
            'Cities';            
            }; 
  %      save ('plotvalue')
%         figure,contour(squeeze(plotvalue(:,18,:)));
%         figure,pcolor(squeeze(plotvalue(:,18,:)));
        shading flat;
        figure, hold on, 
        for i=1:24 
            subplot(4,6,i)
            surf(squeeze(plotvalue_y(:,i,:)));
            axis([1,12, 1,15 0 0.2])
            shading interp
            title(le{i})
        end

    
   %  save ('plotvalues')        ;

        
        
        
    case 'make_fire_data'
        %loads the land use map and converts it into ...
        %extends of the map -28.8371 -36.0246 (left top) (down?)
        %57.9219 46,0021   right bottom
        %cell size : 0,00892857   0,00892857 i guess it is degrees
        %columns 9717 rows 9187
        %task fuer jedes (halbe?) grad muss der Bereich lokalisiert werden
        %und die Anteile des Gross Pixels an den verschiedenen Coverclassen
        %         %berechnet werden. 
        %         ersteinmal berechnung der Pixelposition
        %         also um den Pixel 16 grad ost und 2 grad nord zu finden (groesstenteils forrest cover)
        %         muss man ungef�hr bei 5000 4800 landen.
        %         est-west: -28.8371 bis 57.9219= 86.7590
        %          size use :  9187        9717 also sind die columns in der 2. Dimension und die rows in der ersten wie erwartet
        %         also 86.7590/9717 =0.00892857 sollte also in Ordnung sein.         
        %         also pixel -16,2 ist (-28-16)/0.00892857=4900 kommt also hin. 
        %         
        %         rengridde entsprechend Africa_05 auf x (in diesem Fall 0.5) grad, gehe die Pixelliste durch, 
        %         finde zentralpixel und dann summiere die umgebenden Pixel fuer jede der 28 klassen auf.
        %         bei 0.5 grad sind 0.5/0.00892857 also genau 56 *56 Pixel zu betrachten und bei 
        %         ein grad raster entsprechend 112*112 Pixel es ergibt sich also eine Liste mit 27 eintr�gen der Pixel 
        %         also 10047 (aus Africa05) *27 was ungef�hr ein fuenftel der Africa Karte darstellt.
        dist=0.5;
        use=imread('E:\Climate\Cover\Grid\africa_v511.tif');
        if dist==0.5
            coor=load ('firedata.txt');
            for line=1:size(coor,1)
                x=coor(line,1);
                y=coor(line,2);
                
                xuse=round((x+28.8371)/0.0089285714) ;% das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
                yuse=round((y+36.0246)/0.0089285714) ;%
% oder
%                 xuse=round((lon+28.8371)/0.00892857) ;% das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
%                 yuse=round((lat+36.0246)/0.00892857) ;%
% 
%         for lat=-35:5:35
%                     lat
%                     tot=sum(sum(use(9187-round((lat+5+36.0246)/0.00892857):9187-round((lat+36.0246)/0.00892857),:)==i));
%         



                for ii=0:28
                    alloutputproc(ii+1)=sum(sum(use(9187-yuse-27:9187-yuse+28,xuse-27:xuse+28)==ii));                    
                end                
                % jetzt sortieren wir die noch und dann werden die ersten
                % 10 reingeschrieben
                [alloutputproc, alloutputuse]=sort(-alloutputproc);
                alloutputuse(alloutputproc==0)=0;
                output(line,1:10)=alloutputuse(1:10);
                output(line,11:20)=-alloutputproc(1:10);
                clear('alloutputproc','alloutputuse');
                
            end
        end
    output(:,11:20)=output(:,11:20)/3136;
    save ('fireuse','output');
    
    
    case 'read_hdf'                
        firevalues=[7,8]
        file=varargin{2};
        if nargin==3
            unix=1;
            slash='/';
        else
            unix=0;
            slash='\';
        end
        allnr=0;
        all_files{1}=[];
        zipnr=0;
        zip_files{1}=[];
        
        if isempty(strfind(file,'.hdf')) &  isempty(strfind(file,'.zip'))% dann ist es ein Verzeichniss
            direc=file;
            direczips=direc;
            if unix==0
                if direc(size(direc,2))~='\';
                    direc(size(direc,2)+1)='\';
                end
            else
              if direc(size(direc,2))~='/';
                direc(size(direc,2)+1)='/';                
              end
            end
          verz=dir(file);
            for i=1:size(verz,1)
                if ~isempty(strfind(verz(i).name,'.hdf'))
                    allnr=allnr+1;
                    all_files{allnr}=verz(i).name;
                end
            end
            for i=1:size(verz,1)
                if ~isempty(strfind(verz(i).name,'.zip'))
                    zipnr=zipnr+1;
                    zip_files{zipnr}=verz(i).name;
                    
                end
            end            
        elseif ~isempty(strfind(file,'.zip'))
            zip_files{1}=file;
            zip_nr=1;
        elseif ~isempty(strfind(file,'.hdf'))
            all_files{1}=file;
            direc='';
        else
            'keine files zur bearbeitung gefunden'
            return
        end
        if zipnr>0
            load MODISFIRE
            load ('landuses','use');
            for zipnr=1:size(zip_files,2)
                zipdirstr=strcat(direczips,slash,zip_files{zipnr});
                if unix==1
                    zipdirstr
                    direczips
                    eval (['! unzip ', zipdirstr,' -x *.xml *h22v05* *h23v05* *h22h06* *h23v06* *h16v09* *h17v09* *h23v09* *h23v10* *h16v10* *h17v10* *h18v10* *h16v11* *h17v11* *h18v11* *h16v12* *h23v11* *h17v12* *h18v12* *h21v12* *h22v12* *h23v12* ' ]);                      
                    % downscale ('read_hdf',strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')),'unix');
                    % zur Beschleunigung steht der code hier nocheinmal....                    
                    verz=dir(strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')));
                    direc=strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip',''),slash);
                    for i=1:size(verz,1)
                        if ~isempty(strfind(verz(i).name,'.hdf'))
                            allnr=allnr+1;
                            all_files{allnr}=verz(i).name;
                        end
                    end
                    for allnr=1:size(all_files,2)
                        all_files{allnr};
                        % mal schauen ob wir das file schon hatten
                        filefound=0;
                        if ~isempty(readfiles(1).filelist)
                            for i=1:size (readfiles,2)
                                for ii=1:size (readfiles(i).filelist,2)
                                    filefound=max(strcmp (readfiles(i).filelist{ii},all_files{allnr}),filefound);                                    
                                end
                            end
                        end

                        if filefound==0                    %                    ersteinmal das Datum finden zum eintragen.                            
                            if unix==1
                                ord=strrep(strcat(direc,all_files{allnr}),'\','/');
                            else
                                ord=strrep(strcat(direc,all_files{allnr}),'/','\');
                            end
                            ord
                            fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','most confident detected fire');     
                            if isempty (fire)
                                fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','FireMask');     
                            end
                                
                            [il,is]=find(fire==8 | fire==7 | fire==9); % look for fires
                            
                            %und die info
                            info= hdfinfo(strcat(direc,all_files{allnr}));
                            strinfo=strrep(info.Attributes(2).Value,'(','');
                            strinfo=strrep(strinfo,')','');
                            upperstart=findstr(strinfo,'UpperLeftPointMtrs=');
                            upperend=findstr(strinfo,'		LowerRightMtrs=');
                            lowerend=findstr(strinfo,'		Projection');
                            projstart=findstr(strinfo,'ProjParams=')+size('ProjParams=',2);
                            projend=findstr(strinfo,',0,0,0,0,0,0,0,0,0,0,0,0')-1;            
                            UL=str2num(strinfo(upperstart+size('UpperLeftPointMtrs=',2):upperend-1));
                            LR=str2num(strinfo(upperend+size('		LowerRightMtrs=',2):lowerend-1));            
                            Proj=str2num(strinfo(projstart:projend));
                            datstr=strrep(info.Attributes(4).Value,'-','');
                            daystra=findstr(datstr,'DAYSOFYEAR');            
                            daystrd=findstr(datstr(daystra(1):daystra(2)),'"');
                            date=str2num(datstr(daystra(1)+daystrd(1):daystra(1)+daystrd(2)-2))             ;
                            %finde das richtige datum
                            h=str2num(all_files{allnr}(findstr(all_files{allnr},'h')+1:findstr(all_files{allnr},'h')+2));
                            v=str2num(all_files{allnr}(findstr(all_files{allnr},'v')+1:findstr(all_files{allnr},'v')+2));
                            datfound=0;
                            if isempty(readfiles(1).datum)                                            
                                readfiles(1).datum{1}=date;
                                readfiles(1).filelist{1}=all_files{allnr};
                                readfiles(1).tiles{1}=zeros(8)-1;;
                                readfiles(1).tiles{1}(h-15,v-4)=size(il,1);
                            else
                                for i=1:size (readfiles,2)
                                    if (readfiles(i).datum{1}==date)
                                        readfiles(i).filelist{size(readfiles(i).filelist,2)+1}=all_files{allnr};
                                        readfiles(i).tiles{1}(h-15,v-4)=size(il,1);
                                        datfound=1;                        
                                    end
                                end
                                if datfound==0
                                    readfiles(size(readfiles,2)+1).datum{1}=date;
                                    readfiles(size(readfiles,2)).filelist{1}=all_files{allnr}; 
                                    readfiles(size(readfiles,2)).tiles{1}=zeros(8)-1;                                    
                                    readfiles(size(readfiles,2)).tiles{1}(h-15,v-4)=size(il,1);
                                end
                            end


                            if ~isempty(il)                                
                                %find all fires
                                XDIM=1200;
                                %calculate lat und long for them
                                qual=fire(find(fire==7 | fire==8 | fire==9));
                                x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1);
                                y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2);
                                lat=360*(y./(Proj*2*pi));
                                lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)));
                                xuse=round((lon+28.8371)/0.00892857);
                                yuse=round((lat+36.0246)/0.00892857);
                                if ~isempty (firelist)
                                    oldsize=size(firelist,1);         
                                else
                                    oldsize=0;
                                end
                                uses=0;
                                for i=1:size(lon,1)
                                    uses(i)=use(9187-round((lat(i)+36.0246)/0.00892857),round((lon(i)+28.8371)/0.00892857));
                                end
                                firelist(oldsize+1:oldsize+size(lat,1),1)=lat;
                                firelist(oldsize+1:oldsize+size(lat,1),2)=lon;
                                firelist(oldsize+1:oldsize+size(lat,1),3)=date;
                                firelist(oldsize+1:oldsize+size(lat,1),4)=qual;
                                firelist(oldsize+1:oldsize+size(lat,1),5)=uses;
                                strcat ('found_ ',num2str(size(lat,1)),'_fires at_',num2str(date), '_in_',strcat(direc,all_files{allnr})) 
                            end
                            %hier wird getested ob die gespeicherten Werte zu gross werden.
                            save ('MODISFIRE','firelist','readfiles');
                            if prod(size(firelist))+prod(size(firelist))>30000000 % das ist der Windowswert
                                save (strcat('MODISFIRELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'firelist');
                                save (strcat('MODISFLELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'readfiles');
                                save (strcat('allessicher',strrep(strrep(num2str(clock),' ',''),'.','')));                                
                                firelist=[];
                                save ('MODISFIRE','firelist','readfiles');                                          
                            end
                        end
                    end % das file hatten wir schon mal
                    
                else  % Windows                  
                    unzip(strcat(direc,zip_files{zipnr}));   
                    cd (strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')));                  
                    del ('*.xml');
                    delarray=[                    16,5; 
                        21,5; 
                        22,5;
                        23,5;                   
                        22,6;
                        23,6;
                        16,9;
                        17,9;
                        23,9;
                        23,10;
                        16,10;
                        17,10;
                        18,10;
                        16,11;
                        17,11;
                        18,11;
                        16,12;
                        23,11;
                        17,12;
                        18,12;
                        21,12;                    
                        22,12;
                        23,12;
                        ];
                    
                    for i=1:size (delarray,1)
                        if delarray(i,2)<10                                           
                            delete (strcat('*h',num2str(delarray(i,1)),'v0',num2str(delarray(i,2)),'*'));
                        else
                            delete (strcat('*h',num2str(delarray(i,1)),'v',num2str(delarray(i,2)),'*'));
                        end
                    end
                    cd ..
                    cd ..                
                    %achtung ich werrde jetzt recursiv!
                    downscale ('read_hdf',strcat('PullDir',slash,strrep(zip_files{zipnr},'.zip','')));            
                end


                rmdir('PullDir','s')
            end
        end

        rekursiv=0;
        if unix==0 & ~isempty(all_files{1}) % weil windows is t noch rekursiv
            load MODISFIRE
            load ('landuses','use');
             for allnr=1:size(all_files,2)
                all_files{allnr};
                % mal schauen ob wir das file schon hatten
                filefound=0;
                if ~isempty(readfiles(1).filelist)
                    for i=1:size (readfiles,2)
                        for ii=1:size (readfiles(i).filelist,2)
                            filefound=max(strcmp (readfiles(i).filelist{ii},all_files{allnr}),filefound);                                    
                        end
                    end
                end
                if filefound==0
                    %                    ersteinmal das Datum finden zum eintragen.
                    
                    if unix==1
                        ord=strrep(strcat(direc,all_files{allnr}),'\','/');
                    else
                        ord=strrep(strcat(direc,all_files{allnr}),'/','\');
                    end
                    ord 
                    fire = hdfread(ord,'MODIS_Grid_8Day_Fire','Fields','most confident detected fire');                    
                    [il,is]=find(fire==8 | fire==7 | fire==9); % look for fires
                    
                    %und die info
                    info= hdfinfo(strcat(direc,all_files{allnr}));
                    strinfo=strrep(info.Attributes(2).Value,'(','');
                    strinfo=strrep(strinfo,')','');
                    upperstart=findstr(strinfo,'UpperLeftPointMtrs=');
                    upperend=findstr(strinfo,'		LowerRightMtrs=');
                    lowerend=findstr(strinfo,'		Projection');
                    projstart=findstr(strinfo,'ProjParams=')+size('ProjParams=',2);
                    projend=findstr(strinfo,',0,0,0,0,0,0,0,0,0,0,0,0')-1;            
                    UL=str2num(strinfo(upperstart+size('UpperLeftPointMtrs=',2):upperend-1));
                    LR=str2num(strinfo(upperend+size('		LowerRightMtrs=',2):lowerend-1));            
                    Proj=str2num(strinfo(projstart:projend));
                    datstr=strrep(info.Attributes(4).Value,'-','');
                    daystra=findstr(datstr,'DAYSOFYEAR');            
                    daystrd=findstr(datstr(daystra(1):daystra(2)),'"');
                    date=str2num(datstr(daystra(1)+daystrd(1):daystra(1)+daystrd(2)-2))             ;
                    %finde das richtige datum
                    h=str2num(all_files{allnr}(findstr(all_files{allnr},'h')+1:findstr(all_files{allnr},'h')+2));
                    v=str2num(all_files{allnr}(findstr(all_files{allnr},'v')+1:findstr(all_files{allnr},'v')+2));
                    datfound=0;
                    if isempty(readfiles(1).datum)                                            
                        readfiles(1).datum{1}=date;
                        readfiles(1).filelist{1}=all_files{allnr};
                        readfiles(1).tiles{1}=zeros(8)-1;;
                        readfiles(1).tiles{1}(h-15,v-4)=size(il,1);
                    else
                        for i=1:size (readfiles,2)
                            if (readfiles(i).datum{1}==date)
                                readfiles(i).filelist{size(readfiles(i).filelist,2)+1}=all_files{allnr};
                                readfiles(i).tiles{1}(h-15,v-4)=size(il,1);
                                datfound=1;                        
                            end
                        end
                        if datfound==0
                            readfiles(size(readfiles,2)+1).datum{1}=date;
                            readfiles(size(readfiles,2)).filelist{1}=all_files{allnr};   
                            readfiles(size(readfiles,2)).tiles{1}(h-15,v-4)=size(il,1);
                        end
                    end
                                      
                    
                    if ~isempty(il)
                        
                        %find all fires
                        XDIM=1200;
                        %calculate lat und long for them
                        [il,is]=find(fire==7 | fire==8 | fire==9);
                        qual=fire(find(fire==7 | fire==8 | fire==9));
                        x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1);
                        y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2);
                        lat=360*(y./(Proj*2*pi));
                        lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)));
                        xuse=round((lon+28.8371)/0.00892857);
                        yuse=round((lat+36.0246)/0.00892857);
                        if ~isempty (firelist)
                            oldsize=size(firelist,1);         
                        else
                            oldsize=0;
                        end
                        uses=0;
                        for i=1:size(lon,1)
                            uses(i)=use(9187-round((lat(i)+36.0246)/0.00892857),round((lon(i)+28.8371)/0.00892857));
                        end
                        firelist(oldsize+1:oldsize+size(lat,1),1)=lat;
                        firelist(oldsize+1:oldsize+size(lat,1),2)=lon;
                        firelist(oldsize+1:oldsize+size(lat,1),3)=date;
                        firelist(oldsize+1:oldsize+size(lat,1),4)=qual;
                        firelist(oldsize+1:oldsize+size(lat,1),5)=uses;
                        strcat ('found_ ',num2str(size(lat,1)),'_fires at_',num2str(date), '_in_',strcat(direc,all_files{allnr})) 
                    end
                    %hier wird getested ob die gespeicherten Werte zu gross werden.
                    save ('MODISFIRE','firelist','filelist','readfiles');
                    if prod(size(firelist))+prod(size(firelist))>30000000 % das ist der Windowswert
                        save (strcat('MODISFIRELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'firelist');
                        save (strcat('MODISFLELIST',strrep(strrep(num2str(clock),' ',''),'.','')),'readfiles');
                        firelist=[];
                        save ('MODISFIRE','firelist','readfiles');                                          
                    end
                end
            end % das file hatten wir schon mal
                %            figure(4);
%            scatter(lon,lat);
%            % This part displayes tile and land use
%             is=[0,1199];
%             il=[0,1199];
%             x=((is+0.5).*((LR(1)-UL(1))/XDIM))+UL(1)
%             y=((il+0.5).*((LR(2)-UL(2))/XDIM))+UL(2)
%             lat=360*(y./(Proj*2*pi))
%             lon=360*(x./(cos(lat/180*pi)*(Proj*2*pi)))
%             figure(1)
%             pcolor(double((fire)));
%             shading flat
%             clear fire;           
%             load ('landuses','use');
%             xuse=round((lon+28.8371)/0.00892857) % das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
%             yuse=round((lat+36.0246)/0.00892857)
%             clear fire;
% %             size(double(use(xuse(1):use(xuse(2),yuse(2):yuse(1)))))
%             figure(2)
%             pcolor(double(use(yuse(2):yuse(1),xuse(1):xuse(2))));
%             shading flat
            
        end % for allfiles
        
    case 'convert_netcdftxt'
        gesammtngrid=[];
        file=varargin{2};
        if isempty(strfind(file,'.txt')) % dann ist es ein Verzeichniss
            verz=dir(file);
        else
            verz(1).name=file;
            file='';
        end
        for i=1:size (verz,1)
            if ~isempty(strfind(verz(i).name,'.txt'))                    
                strcat('lese:',file,verz(i).name)
                newngrid =load(strcat(file,verz(i).name));
                if nargin>2
                    timesteps=varargin{3};
                    xdim=varargin{4};
                    ydim=varargin{5};
                else
                    xdim=192;%144   temperature (192,94)  blitze(144,73)
                    ydim=94; %73
                    timesteps=prod(size(newngrid))/192/94; % wegen Schaltjahr
                    if mod(timesteps,1)~=0 
                        'dimensionen falsch'
                        return
                    end
                end               
                newngrid =reshape(newngrid',prod(size(newngrid)),1);
                newngrid =reshape(newngrid',xdim,ydim,timesteps);
                % set africa zusammen
                newngrid(193:222,:,:)=newngrid(1:30,:,:);
                newngrid=newngrid(185:221,29:66,:);        
                gesammtngrid(:,:,size(gesammtngrid,3)+1:size(gesammtngrid,3)+size(newngrid,3))=newngrid; 
                save (strrep(verz(i).name,'.txt',''),'gesammtngrid');            
            end 
           
    
        end
        
%         for m=1:12 
%             iii=0;
%             if m<10 
%                 mon=load
%                 (strcat('mon0',num2str(m),'.dat'));
%                 
%             else
%                 mon=load (strcat('mon',num2str(m),'.dat'));,
%             end, 
%             for i=1:size(mon,1),
%                 for ii=1:size(mon,2),
%                     iii=iii+1;out(iii)=mon(i,ii);,
%                 end,
%             end,
%             pc=reshape(out,144,73)';,
%             pc=flipdim(pc,1);
%             pc(:,145:216)=pc(:,1:72);,
%             pc(:,1:72)=[];winde(:,:,m)=pc;,,
%         end
     %vwind=load('E:\Climate\Wind\vwindday.txt');
     %>> uwind=load('E:\Climate\Wind\uwindday.txt');
 %reuwind=reshape(uwind',3836880,1);
     %pc=reshape(reuwind,144,73,365);
%pc(145:216,:,:)=pc(1:72,:,:);
% pc(1:72,:,:)=[];
%>> pc=flipdim(pc,2);
%>> figure,pcolor(squeeze(double(pc(:,:,1)))'), shading flat
% for i=1:365,outu(:,:,i)=squeeze(double(pc(:,:,i)))';,end
    case 'read_fire'
        direc='E:\Climate\Fire\unzip';
        fireout1=[];
        fireout2=[];
        dirstr=dir(direc);
        for i=3:size (dirstr,1)
            dirstr(i).name
            if ~isempty(findstr(dirstr(i).name,'1.F'))  %alg 1
                if ~isempty(findstr(dirstr(i).name,'ESA'))
                    fid=fopen (strcat(direc,'\',dirstr(i).name));
                    line=1;
                    while 1
                        tline = fgetl(fid);
                        if ~ischar(tline), break, end
                        for ii=1:4
                            [value tline]=strtok(tline);
                            if ii>2
                                firemon1(line,ii-1)=str2num(value);                       
                            elseif ii==1
                                firemon1(line,1)=str2num(value);                       
                            end
                            %Line format = [Date Time Latitude Longitude NDVI StationEOL] (Record length = 46)

                        end
                        line=line+1;
                    end
                    fclose(fid);
                    
                else
                    firemon1=load((strcat(direc,'\',dirstr(i).name)));
                    %kick out orbit and time
                    firemon1(:,2:3)=[];
                    %Line format = [Date Time Latitude Longitude NDVI StationEOL] (Record length = 46)

                end
               
                fireout1(size(fireout1,1)+1:size(fireout1,1)+size(firemon1,1),:)=firemon1;
                size (fireout1)
            else % alg 2
                if ~isempty(findstr(dirstr(i).name,'ESA'))
                    fid=fopen (strcat(direc,'\',dirstr(i).name));
                    line=1;
                    while 1
                        tline = fgetl(fid);
                        if ~ischar(tline), break, end
                        for ii=1:4
                            [value tline]=strtok(tline);
                            if ii>2
                                firemon2(line,ii-1)=str2num(value);                       
                            elseif ii==1
                                firemon2(line,1)=str2num(value);                       
                            end
                        end
                        line=line+1;
                    end
                    fclose(fid);                    
                else
                    firemon2=load(strcat(direc,'\',dirstr(i).name));
                    %kick out orbit and time
                     %Line format = [Date Orbit Time Latitude Longitude] (Record length = 66)

                    firemon2(:,2:3)=[];                    
                end
                fireout2(size(fireout2,1)+1:size(firemon2,1)+size(fireout2,1),:)=firemon2;
                size (fireout2)
            end

        end
        fireout1=fireout1(fireout1(:,3)>-18 & fireout1(:,3)<52 & fireout1(:,2)<37 & fireout1(:,2)>-35,:);
        fireout2=fireout2(fireout2(:,3)>-18 & fireout2(:,3)<52 & fireout2(:,2)<37 & fireout2(:,2)>-35,:);
        fireout1(fireout1(:,1)<30000,1)=fireout1(fireout1(:,1)<30000,1)+20000000; % account for different file formats
        fireout1(fireout1(:,1)<20000000,1)=fireout1(fireout1(:,1)<20000000,1)+19000000;
        fireout2(fireout2(:,1)<30000,1)=fireout2(fireout2(:,1)<30000,1)+20000000;
        fireout2(fireout2(:,1)<20000000,1)=fireout2(fireout2(:,1)<20000000,1)+19000000;
%         [newngrid, R]=downscale('read_only',0.5,0,'Africa_05.txt','',1);    
%         newngrid(newngrid>0)=1;
%         % africa05 is 0.5 also *2 
%         %totlat =   -34   102
%         %totlon =   -69    74
%         %die sind dazuzuaddieren: Code in readonly 
%         %totlat =[min(plotngrid(:,1)) max(plotngrid(:,1))];
%         %totlon =[min(plotngrid(:,2)) max(plotngrid(:,2))];        
%         %plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
%         %plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
%         %newngrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,col(1))));
%         totlat = [  -34   102]
%         totlon =[   -69    74]
%         fireout1(:,4)=round(fireout1(:,3)-(totlat(:,1))+1); %round corrects calculation errors by matlab
%         fireout1(:,5)=round(fireout1(:,2)-(totlon(:,1))+1);
%         for i=1:size(fireout,1)
%             find (newngrid(fireout1(:,4),fireout1(:,5)));
%         
%         gehe direkt auf die land use karte ein und versuche jeder landuse klasse noch eine 
%             
%             
%             %kick out australia and so on
 save ('fires','fireout1','fireout2');
%        firefreq=zeros(28,10);
     
%         
%         for year=1:1
%         % erstaml test
%         firemon=load('E:\Climate\Fire\unzip\200506ALGO2.FIRE');  % data format Line format = [Date Orbit Time Latitude Longitude] (Record length = 66)
%         %kick out orbit and time
%         firemon(:,2:3)=[];
%         %kick out australia and so on 
%         firemon=firemon(firemon(:,2)>-18 & firemon(:,2)<52 & firemon(:,3)<37 & firemon(:,3)>-35,:);
%         for i=1:size (firemon,1) % finde landuse
%             xuse=round((x+28.8371)*0.00892857) ;% das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
%             yuse=round((y+36.0246)*0.00892857) ;%
%             if use(xuse,yuse)==0, 'problem', xuse, yuse,else
%                 firefreq(use(xuse,yuse),day)=firefreq(use(xuse,yuse),year)+1;
%             end
%         end
%         
%         
%         
%         
% %           
%             
%         %count fires in the month 

    downscale('build_fire_liste');
    case 'build_fire_liste'
        load ('fires');
        %save ('fires','fireout1','fireout2');        
        use=imread('E:\Climate\Cover\Grid\africa_v511.tif');
        for i=1:2
            if i==1
                fire=fireout1;
            else
                fire=fireout2;
            end
            for line=1:size(fire,1)
%                 xuse=round((fire(line,3)+28.8371)/0.00892857) % das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
%                 yuse=round((fire(line,2)+36.0246)/0.00892857) %
                fire(line,4) =use(9187-round((fire(line,2)+36.0246)/0.00892857),round((fire(line,3)+28.8371)/0.00892857));
            end
            if i==1
                fireout1=fire;
            else
                fireout2=fire;
            end            
        end
        fireout1(fireout1(:,4)==0,:)=[];
        fireout2(fireout2(:,4)==0,:)=[];
        save ('landuses');
    case 'landuse_totals'
        %load('fires')
        load ('landuses')
        use=imread('E:\Climate\Cover\Grid\africa_v511.tif');
        for i=1:21 % without desert & cities
            if i~= 5 & i~= 6 & i~= 17
                for lat=-35:5:35
                    lat
                    tot=sum(sum(use(9187-round((lat+5+36.0246)/0.00892857):9187-round((lat+36.0246)/0.00892857),:)==i));
                    if tot>100
                        plotvalue(lat/5+8,i)=size(find (fireout1(:,2)>lat & fireout1(:,2)<lat+5 & fireout1(:,4)==i),1)/tot;
                        plotvalue2(lat/5+8,i)=size(find (fireout2(:,2)>lat & fireout2(:,2)<lat+5 & fireout2(:,4)==i),1)/tot;
                    else
                        plotvalue(lat/5+8,i)=-0.05;
                        plotvalue2(lat/5+8,i)=-0.05;
                    end
                end
            end
        end
        bar3(plotvalue);
        le={'Closed evergreen lowland forest';
            'Degraded evergreen lowland forest';
            'Submontane forest (900 -1500 m)';
            'Montane forest (>1500 m)';
            'Swamp forest';
            'Mangrove';
            'Mosaic Forest / Croplands';
            'Mosaic Forest / Savanna';
            'Closed deciduous forest';
            'Deciduous woodland';
            'Deciduous shrubland with sparse trees';
            'Open deciduous shrubland';
            'Closed grassland';
            'Open grassland with sparse shrubs';
            'Open grassland';
            'Sparse grassland';
            'Swamp bushland and grassland';
            'Croplands (>50%)';
            'Croplands with open woody vegetation';
            'Irrigated croplands';
            'Tree crops'}; 
        legend (le);
        save ('plots')
    
    
    
    
    
    
    
    case 'plot_over_time_MODIS' 
        clear
        %load ('landuses','use')
        
       % use=imread('E:\Climate\Cover\Grid\africa_v511.tif');
%         size_1=size(use,1);
%         
%         for i=1:24 % without desert & cities
%             for lat=-37.5:5:37.5
%                 tot(lat/5+8.5,i)=sum(sum(use(max(1,9187-round((lat+5+36.0246)/0.00892857)):min(size_1,9187-round((lat+36.0246)/0.00892857)),:)==i));
%             end
%         end
%         save ('totuse','tot');
%         clear use
%         pack;
% %         
        load  ('totuse','tot');
        months=0;
        load ('MODISALL','allfires');
        for time=20000000:100:20070000
            if mod(time,10000)<=1200
                months=months+1,time
                for i=18:18%i=1:21 % without desert & cities
                    %if i~= 5 & i~= 6 & i~= 17
                        for lat=-35:5:35
                            if tot(lat/5+8,i)>50
                                plotvalue(lat/5+8,i,months)=size(find (allfires (:,1)>=lat & allfires(:,1)<lat+5 & allfires(:,5)==i  & allfires(:,3)>=time & allfires(:,3)<time+100 ),1)/tot(lat/5+8,i);
                                %plotvalue2(lat/5+8,i,months)=size(find (fireout2(:,2)>lat & fireout2(:,2)<lat+5 & fireout2(:,4)==i  & fireout2(:,1)>=time & fireout2(:,1)<time+100 ),1)/tot(lat/5+8,i);
                            else
                                plotvalue(lat/5+8,i,months)=0;
%                                plotvalue2(lat/5+8,i,months)=0;
                            end
                        end
                    %end
                end
            end
        end
 save 'firetemp'
        figure,contour(squeeze(plotvalue(:,18,:)));
        figure,pcolor(squeeze(plotvalue(:,18,:)));
        shading flat;
 %       figure,contour(squeeze(plotvalue2(:,18,:)));
 %       figure,pcolor(squeeze(plotvalue2(:,18,:)));
 %       shading flat;
       % calculate a averaged picture:
       % kick out the first two months
        plotvalue(:,:,1:2)=[];
        %southern parts burn in winter, northern in the summer
        for i=1:7
            for year=1:11
                if size (plotvalue,3)>=year*12+6
                    plotvalueeq(i,year,:)=plotvalue(i,year,:)./sum(plotvalue(i,year*12-6:year*12+6,:),3);
                end
                if size (plotvalue,3)>=year*12+11                    
                    plotvalueeq(i+7,year,:)=plotvalue(i+7,year,:)./sum(plotvalue(i+7,year*12-11:year*12+11,:),3);
                end
            end
        end
    
    
    case 'plot_over_time'
        
        load ('landuses')
       % use=imread('E:\Climate\Cover\Grid\africa_v511.tif');
        months=0;
        for i=1:21 % without desert & cities
            if i~= 5 & i~= 6 & i~= 17
                for lat=-35:5:35
                    tot(lat/5+8,i)=sum(sum(use(9187-round((lat+5+36.0246)/0.00892857):9187-round((lat+36.0246)/0.00892857),:)==i));
                end
            end
        end
        for time=19951100:100:20060400
            if mod(time,10000)<=1200
                months=months+1,time
                for i=1:21 % without desert & cities
                    if i~= 5 & i~= 6 & i~= 17
                        for lat=-35:5:35
                            if tot(lat/5+8,i)>50
                                plotvalue(lat/5+8,i,months)=size(find (fireout1(:,2)>lat & fireout1(:,2)<lat+5 & fireout1(:,4)==i  & fireout1(:,1)>=time & fireout1(:,1)<time+100 ),1)/tot(lat/5+8,i);
                                plotvalue2(lat/5+8,i,months)=size(find (fireout2(:,2)>lat & fireout2(:,2)<lat+5 & fireout2(:,4)==i  & fireout2(:,1)>=time & fireout2(:,1)<time+100 ),1)/tot(lat/5+8,i);
                            else
                                plotvalue(lat/5+8,i,months)=0;
                                plotvalue2(lat/5+8,i,months)=0;
                            end
                        end
                    end
                end
            end
        end
 save 'firetemp'
        figure,contour(squeeze(plotvalue(:,18,:)));
        figure,pcolor(squeeze(plotvalue(:,18,:)));
        shading flat;
        figure,contour(squeeze(plotvalue2(:,18,:)));
        figure,pcolor(squeeze(plotvalue2(:,18,:)));
        shading flat;
       % calculate a averaged picture:
       % kick out the first two months
        plotvalue(:,:,1:2)=[];
        %southern parts burn in winter, northern in the summer
        for i=1:7
            for year=1:11
                if size (plotvalue,3)>=year*12+6
                    plotvalueeq(i,year,:)=plotvalue(i,year,:)./sum(plotvalue(i,year*12-6:year*12+6,:),3);
                end
                if size (plotvalue,3)>=year*12+11                    
                    plotvalueeq(i+7,year,:)=plotvalue(i+7,year,:)./sum(plotvalue(i+7,year*12-11:year*12+11,:),3);
                end
            end
        end
        
    case 'land_uses_per_pixel'
       
        load ('landuses','use');
        coor=load ('Africa_05.txt') ;
        writedata=zeros(size(coor,1),20);
        for line=1:size(coor,1)
            %                 xuse=round((fire(line,3)+28.8371)/0.00892857) % das ist der Zentralpixel nun an einer Seite 28 dazu und an der anderen 27 dazu  
            %                 yuse=round((fire(line,2)+36.0246)/0.00892857) %
            uses=unique(double(reshape((use(9187-round((coor(line,2)+36.0246)/0.00892857)-28:9187-round((coor(line,2)+36.0246)/0.00892857)+27,round((coor(line,1)+28.8371)/0.00892857)-28:round((coor(line,1)+28.8371)/0.00892857)+27)),3136,1)))';                
            if size(uses,2)>10
                uses=uses(1,1:10);            
            end
            if size(uses,2)>1                
                perc=hist(double(reshape((use(9187-round((coor(line,2)+36.0246)/0.00892857)-28:9187-round((coor(line,2)+36.0246)/0.00892857)+27,round((coor(line,1)+28.8371)/0.00892857)-28:round((coor(line,1)+28.8371)/0.00892857)+27)),3136,1)),uses)./3136;            
            else
                perc=1;
            end
           
            writedata(line,1:size(uses,2))=uses;
            writedata(line,11:size(perc,2)+10)=perc;
            if mod(line,1000)==0
                line
            end
        end
        save ('landuseliste','writedata')
            
    case 'get_climate'
        %the next step is to make a list of all needed cells to which to get the climate data, to be read in by guess.cpp all
        % then this data has to be put into different files (one for each
        % year?) afterwards the Nicholson index has to be calculated for
        % each fire event in future and backwards, plus I can try to fiddle
        % around with precipitation only 
    case 'classify'
  
        offset=0;
        ext='';
        numberoffiles=1;
        newcelldist=1;
        col=-1; 
        plot =0;
        displayyear=-20;
        map=0;
        histo=0;
        value_all=0;
        jemeter=0;
        minus=0;
        nppclass=1;
        fpc=0;
        plotlais=0;
        for i=1:nargin
            if strcmp(varargin{i},'newcelldist')
                newcelldist=varargin {i+1};
            elseif (strcmp(varargin{i},'filename'))
                filename=varargin{i+1};
            elseif (strcmp(varargin{i},'offset'))
                offset=varargin{i+1};
            elseif (strcmp(varargin{i},'ext'))
                ext=varargin{i+1};
            elseif (strcmp(varargin{i},'numberoffiles'))                
                numberoffiles=varargin{i+1};
            elseif strcmp(varargin{i},'column')                 
                col=varargin{i+1};
            elseif strcmp(varargin{i},'all_column')
                col=0;
            elseif strcmp(varargin{i},'last_year')
                displayyear=-1;
            elseif strcmp(varargin{i},'last_20_years')
                displayyear=-20;
            elseif strcmp(varargin{i},'last_6_years')
                displayyear=-6;
            elseif strcmp(varargin{i},'average')
                displayyear=-varargin{i+1};                
            elseif strcmp(varargin{i},'year')
                displayyear=varargin{i+1};                
            elseif strcmp(varargin{i},'plot')                                 
                plot=1;
            elseif strcmp(varargin{i},'map')                                 
                map=1;
            elseif strcmp(varargin{i},'hist')                 
                %geht natuerlich nur bei t�glichen Werten 
                histo=1;           
            elseif strcmp(varargin{i},'value_all')                 
                %ertellt Werte fuer NHA&SHA, zeigt an und speichert sie 
                value_all=1;
            elseif strcmp(varargin{i},'jemeter')
                jemeter=1;
            elseif strcmp(varargin{i},'minus')                
                minus=1;
            elseif strcmp(varargin{i},'nppclass')                
                nppclass=1;            
            elseif strcmp(varargin{i},'fpc')                
                fpc=1;
            elseif strcmp(varargin{i},'plotlais')                
                plotlais=1;
            end
        
        end
        %         %[totalngrid R]=downscale('read_only',newcelldist,offset,filename,ext,numberoffiles,'column',[18 16 17 4 5 6 11 12 13 14 15]); % all pfts
        temp=load (strcat(filename,'/lai.out'));
        if size(temp,2)==13
            [totalngrid R]=downscale('read_only','filename',strcat(filename,'/lai.out'),'column',[13 4 5 6 7 8 9 10 11 12 ],  'offset',offset,'last_6_years','jemeter');
        else
            [totalngrid R]=downscale('read_only','filename',strcat(filename,'/lai.out'),'column',[14 4 5 6 7 8 9 10 11 12 13],  'offset',offset,'last_6_years','jemeter');
            % 13 ist shrub
        end

            load ('newngridalle')
        if fpc==1
            grassngrid=squeeze(newngridalle(10,:,:))+squeeze(newngridalle(9,:,:));;
            figure,pcolor(grassngrid)
            totalngrid=squeeze(newngridalle(1,:,:));
            treengrid=totalngrid-grassngrid;    
            figure,pcolor(treengrid)
            figure,pcolor(totalngrid)
            
        else 
            TrBE=squeeze(newngridalle(2,:,:))+squeeze(newngridalle(3,:,:));
            TrBR=squeeze(newngridalle(4,:,:));
            TeBS=squeeze(newngridalle(5,:,:))+squeeze(newngridalle(6,:,:));
            TeNE=squeeze(newngridalle(7,:,:));    
            TeBE=squeeze(newngridalle(8,:,:));                
if size(newngridalle,1)>10
            Shrub=squeeze(newngridalle(11,:,:));                
end
            grassngrid=squeeze(newngridalle(10,:,:))+squeeze(newngridalle(9,:,:));;
            totalngrid=squeeze(newngridalle(1,:,:)); ;
            treengrid=totalngrid-grassngrid;    
            TrTngrid=TrBE+TrBR;
            TeTngrid=TeNE+TeBE+TeBS;        
            classngrid=ones(size(treengrid));
            classngrid(classngrid==1)=NaN;
%            % classngrid(Shrub>0.5 )=5;
%             classngrid(TrTngrid>treengrid*0.5 & treengrid>2.5)=3;                                   %trop seasonal forest  
%             classngrid(TeTngrid>treengrid*0.5 & treengrid>2.5)=4;                                   %temp mixed forest  
%             classngrid(TrBE>treengrid*0.6 & treengrid>2.5)=1;                                       %trop rain forest
%             %classngrid(TrBR>treengrid*0.6 & treengrid>2.5)=2;                                       %trop dec forest                           
%             % ge�ndert zu:
%             classngrid(TrBR>treengrid*0.6 & treengrid>2.5)=5;                                       %war trop dec forest wird nun auch Savanna
%            
%             classngrid(treengrid>0.5 & treengrid<=2.5 & totalngrid>3)=5;                            %moist savannah
%             classngrid(treengrid>0.5 & treengrid<=2.5 & totalngrid<3)=6;                            %dry savannah
%             %classngrid(treengrid<0.5 & grassngrid>3)=7;                                             %tall grassland
%             classngrid(treengrid<0.9 & grassngrid>3)=7;                                             %tall grassland
%             classngrid(treengrid<0.2 & grassngrid>0.5)=8;                                           %dry grassland
%             %classngrid(treengrid<0.1 & grassngrid>0.5)=8;                                           %dry grassland
%             classngrid(treengrid>0.5 & treengrid<2.5 & grassngrid<treengrid)=9;                     %xeric woodland
%             classngrid(treengrid<0.5 & totalngrid>0.1)=10;                                          %arid shrubland / steppe
%             
%             %classngrid(totalngrid<0.2)=11;                                                          %Desert
%             classngrid(TeBS>TrBE & TeBS>TrBR  & TeBS>TeNE  & TeBS>TeBE  & TeTngrid>treengrid*0.8 & treengrid>2.5)=12; 
%             %Temp Br Seas forest       
%             %classngrid(TeMBS>treengrid*0.8 & treengrid>2.5)=11;                                    %trop dec forest       
%             %classngrid(TeIBS>treengrid*0.8 & treengrid>=2.5)=11;                                   %trop dec forest       
%             classngrid(TeNE>TrBE & TeNE>TrBR  & TeNE>TeBS  & TeNE>TeBE &  TeTngrid>treengrid*0.8 & treengrid>2.5)=13; 
%             %Temp Needll Ev forest       
%             classngrid(TeBE>TrBE & TeBE>TrBR  & TeBE>TeBS  & TeBE>TeNE &  TeTngrid>treengrid*0.8 & treengrid>2.5)=14;             
%             %Temp Br Ev forest       
%             %classngrid(Shrub>0.5 )=5;
%             classngrid(treengrid<0.9 & grassngrid>3)=7;                                             %tall grassland
%             classngrid(totalngrid<0.2)=11;                                                          %Desert
           % classngrid(Shrub>0.5 )=5;
            classngrid(((TrBR>TrBE & TrBR>Shrub) | TrBR>treengrid*0.5) & totalngrid>0.5)=2;          %war trop dec forest wird nun auch Savanna           
            classngrid(treengrid<2.5 & treengrid>0.5 )=2;          %war trop dec forest wird nun auch Savanna           
            classngrid(((TrBE>TrBE) | TrBE>treengrid*0.5) & treengrid>2.5)=1;              %trop rain forest                       
  %          classngrid(TrBR>treengrid*0.5 & TrBR>2.5 )=7;                        %trop dec forest
            classngrid(totalngrid<=0.2 | (treengrid<=0.5 & grassngrid<=0.2))=6;%Desert Das letzte ist eine nicht ganz saubere Klasse auus Thomas paper
%            classngrid(grassngrid>(treengrid) & grassngrid>0.2 & treengrid<0.4)=3;   %grassland 
           classngrid(grassngrid>0.2 & treengrid<0.4)=3;   %grassland 
                     
                     %   classngrid(treengrid>0.5 & treengrid<=2.5)=2;                  %moist savannah
            %classngrid(treengrid<0.5 & grassngrid>0.5)=3;                    %tall grassland                                                   %dry grassland
        %    classngrid(treengrid>0.5 & treengrid<2.5 & treengrid-Shrub<Shrub)=4;   %xeric woodland  dense shrub                                
          if size(newngridalle,1)>10
              classngrid(totalngrid>0.5 & (TeNE>treengrid*0.3))=5;          % dense shrubland  conifer forest   
              classngrid(totalngrid>0.5 & (Shrub>totalngrid*0.5 | TeBE>treengrid*0.4))=5;          % open shrubland     
              classngrid(Shrub>totalngrid*0.5 & Shrub>1.5)=4;          % dense shrubland     
              
              
              if plotlais 
                  figure, pcolor(Shrub); shading flat,
                  colorbar,title(strcat ('Shrub_lai',strrep(filename,'\','/')));
              end
          end

          %save
          newngrid=classngrid;
          figure
          pcolor(newngrid);
          shading flat;title(strcat ('Classification_',strrep(filename,'\','/')));
          anzclass=max(unique(newngrid(~isnan(newngrid))));
          %             labels={'rain forest',...%1
          %                 'trop dec forest',...2
          %                 'trop seasonal forest  ',...3
          %                 'trop mixed forest',...4
          %                 'moist savannah',...5
%                 'dry savannah',...6
%                 'tall grassland',...7
%                 'dry grassland'...8
%                 ,'xeric woodland',...9
%                 'arid shrubland / steppe'...10
%                 ,'desert'...11
%                 'Tem Br Dec'  ,...12
%                 'Temp Needll Ev forest'   ,...13
%                 'Temp Br Ev fores'};% 14
%             labels=labels(1:anzclass);
 labels={ 'Trop eg rain for/woodl',...%1          
                'Savanna',...2
                'Grassland Steppe',...3
                'Dense shrubl'...4
                ,'Open shrubl',...5
                'Desert'};%...6            
            colormap(jet(anzclass));
            lcolorbar(labels,'fontweight','bold');
            %         figure 
            %         mapshow(classngrid,R,'displaytype','surface')
            %         
            %         save
            %subplot(1,3,2)
if plotlais
            figure, 
            subplot(4,1,1)
            pcolor(treengrid); shading flat,
            colorbar,title(strcat('TreeLAI_',strrep(strrep(filename,'\','/'),'_','')));
            subplot(4,1,2)
            pcolor(grassngrid);shading flat,
            colorbar,title(strcat ('GrassLAI_',strrep(strrep(filename,'\','/'),'_','')));
            subplot(4,1,3)
            pcolor(treengrid-Shrub);shading flat,
            colorbar,title(strcat ('Tree ohne Shrubs',strrep(strrep(filename,'\','/'),'_','')));
            subplot(4,1,4)
            pcolor(TrBR);shading flat,
            colorbar,title(strcat ('TrBR',strrep(strrep(filename,'\','/'),'_','')));
             
end
       
            %figure
%         %treengrdi
%         figure,pcolor(treengrid./grassngrid).*(treengrid>0.1).*(grassngrid>0.1);shading flat,
%         colorbar,title(strcat ('GrassLAI_',filename));
%Der folgende         teil ist fuer die L3JRC graphen
%         if nppclass==1
%         fluxes=load (strrep(filename,'lai','flux'));
%         maxyear=max(fluxes(:,3));
%         clear fluxes
%             for jahr=maxyear:-1:maxyear-5
%                 [nppgrid R]=downscale('read_only','column',4,'filename',strrep(filename,'lai','flux'),'year',jahr);
%                 nppgrid=nppgrid';            
%                 for cl=1:anzclass
%                     nppclas=nppgrid.*(newngrid==cl);
%                     nppc(jahr-maxyear+6,cl,1:3)=  [-sum(sum(nppclas(1:-round(R(3,2)/R(1,2)),:))),  -sum(sum(nppclas))+ sum(sum(nppclas(1:-round(R(3,2)/R(1,2)),:))),   -sum(sum(nppclas))]*1000/10^12 ;               
%                 end
%             end
%         end
%         savannanpp=squeeze(sum(nppc(:,2:9,:),2));
%         %strcat(num2str([sum(sum(nppgrid(1:-round(R(3,2)/R(1,2)),:)))))  sum(sum(nppgrid))-sum(sum(nppgrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(nppgrid))]/(10^12)*1000), 'Tg')
%         strcat(num2str([sum(sum(nppgrid(1:-round(R(3,2)/R(1,2)),:)))  sum(sum(nppgrid))-   sum(sum(nppgrid(1:-round(R(3,2)/R(1,2)),:)))   sum(sum(nppgrid))]*1000/10^12), 'Tg')
%         pcolor (nppgrid(1:-round(R(3,2)/R(1,2)),:)) %zeigt die        %suedhemisph�re
%         
%         % und nun das ganze fur die emissions     
%         if nppclass==1
%             for jahr=maxyear:-1:maxyear-5
%                 [emisgrid R]=downscale('read_only','column',6,'filename',strrep(filename,'lai','flux'),'year',jahr);
%                 emisgrid=emisgrid';            
%                 for cl=1:anzclass
%                     emisclas=emisgrid.*(newngrid==cl);
%                     emis(jahr-maxyear+6,cl,1:3)=  [-sum(sum(emisclas(1:-round(R(3,2)/R(1,2)),:))),  -sum(sum(emisclas))+ sum(sum(emisclas(1:-round(R(3,2)/R(1,2)),:))),   -sum(sum(emisclas))]*1000/10^12 ;               
%                 end
%             end
%         end
%         savannaemis=-squeeze(sum(emis(:,2:9,:),2));
%         %strcat(num2str([sum(sum(nppgrid(1:-round(R(3,2)/R(1,2)),:)))))  sum(sum(nppgrid))-sum(sum(nppgrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(nppgrid))]/(10^12)*1000), 'Tg')
%         strcat(num2str([sum(sum(emisgrid(1:-round(R(3,2)/R(1,2)),:)))  sum(sum(emisgrid))-   sum(sum(emisgrid(1:-round(R(3,2)/R(1,2)),:)))   sum(sum(emisgrid))]*1000/10^12), 'Tg')
%         %pcolor (nppgrid(1:-round(R(3,2)/R(1,2)),:)) %zeigt die        %suedhemisph�re
%            %     
%         
%         save
        end

    case 'dom_pft'
        filename=varargin{4};
        newcelldist=varargin{2};
        offset=varargin{3};
        ext=varargin{5};
        numberoffiles=varargin{6};
        [totalngrid R]=downscale('read_only','filename',filename,'all_column');
        load ('newngridalle')  
        %find maximum_pft
        %for i=1:max(size(header))
        header{2}='TrTBE';
        header{3}='TrIBE';
        header{4}='TrBR';
        header{5}='BoTNE';
        header{6}='BoMNE';
        header{7}='BoBS';
        header{8}='BoNS';
        header{9}='TeTBS';
        header{10}='TeMBS';
        header{11}='TeIBS';
        header{12}='TeNE';
        header{13}='TeBE';
        header{14}='C3grass';
        header{15}='C4grass';
        header{1}='no value';
        
%         header{1}='TrTBE';
%         header{2}='TrIBE';
%         header{3}='TrBR';
%         header{4}='TeTBS';
%         header{5}='TeMBS';
%         header{6}='TeIBS';
%         header{7}='TeNE';
%         header{8}='TeBE';
%         header{10}='C3grass';
%         header{9}='C4grass';
%         header{11}='total';
%         
        
        
        
        for ii=1: size (newngridalle,2)
            for iii=1: size (newngridalle,3)
                temp=find(newngridalle(:,ii,iii)==max(newngridalle(:,ii,iii)));
                if size(temp,1)==1
                    dom_pft(ii,iii)=temp;
                end
            end
        end
        figure
        newngrid=dom_pft;
        pcolor(newngrid);
        shading flat;
        %labels={'rain forest','dec forest','moist savannah','dry savannah','tall grassland','dry grassland','xeric woodland','arid shrubland / steppe','desert','TeTBS' ,  'TeMBS'  , 'TeIBS'  ,  'TeNE'   , 'TeBE'};
        labels=header;
        colormap(jet(max(size(header))));
        lcolorbar(labels,'fontweight','bold');
%         figure 
%         mapshow(classngrid,R,'displaytype','surface')
    case 'read_only'
        %%[totalngrid R]=downscale('read_only','newcelldist',,'offset',,'filename',,'ext',,'numberoffiles',,'column',[18 16 17 4 5 6 11 12 13 14 15])            
        
        offset=0;
        ext='';
        numberoffiles=1;
        newcelldist=-1;
        col=-1; 
        plot =0;
        displayyear=-20;
        map=0;
        histo=0;
        value_all=0;
        jemeter=0;
        minus=0;
        maxout=0;
        colorm=0;
        pixelsize=0;
        fortran=0;
        degree=1;
        fortrangrid=0;
        white=1;
        read_data=1;
        africa_old=0;
        europe=0;
        sweden=0;
        canada=0;
        africa=0;
        world=0;   
        lonlat=0;
           set_caxis=0;
             maxwerte=0;
        %fileread=0;
        for i=1:nargin
            if strcmp(varargin{i},'newcelldist')
                newcelldist=varargin {i+1};
               
            elseif (strcmp(varargin{i},'filename'))
                filename=varargin{i+1};
                fileread=1;
            elseif (strcmp(varargin{i},'africa_old'))
                africa_old=1;
            elseif (strcmp(varargin{i},'in_data') | (strcmp(varargin{i},'data_in')))
                rengrid=varargin{i+1};
                read_data=0;
            elseif (strcmp(varargin{i},'offset'))
                offset=varargin{i+1};
            elseif (strcmp(varargin{i},'ext'))
                ext=varargin{i+1};
            elseif (strcmp(varargin{i},'numberoffiles'))                
                numberoffiles=varargin{i+1};
            elseif strcmp(varargin{i},'column')                 
                col=varargin{i+1};
            elseif strcmp(varargin{i},'all_column')
                col=0;
            elseif strcmp(varargin{i},'last_year')
                displayyear=-1;
            elseif strcmp(varargin{i},'last_20_years')
                displayyear=-20;
            elseif strcmp(varargin{i},'last_x_years')
                displayyear=-varargin{i+1};
            
            elseif strcmp(varargin{i},'last_6_years')
                displayyear=-6;
            elseif strcmp(varargin{i},'last_8_years')
                displayyear=-8;
                
            elseif strcmp(varargin{i},'endyear_minus')
                displayyear=-varargin{i+1};
            elseif strcmp(varargin{i},'average')
                displayyear=-varargin{i+1};                
            elseif strcmp(varargin{i},'year')                
                displayyear=varargin{i+1};   
            elseif strcmp(varargin{i},'years')                
                displayyear=varargin{i+1};   
          
            elseif strcmp(varargin{i},'plot')                                 
                plot=1;
            elseif strcmp(varargin{i},'map')                                 
                map=1;
            elseif strcmp(varargin{i},'hist')                 
                %geht natuerlich nur bei t�glichen Werten 
                histo=1;    
            elseif strcmp(varargin{i},'pixelsize')                 
                 % bererchnet nur die Pixelsize als map
                pixelsize=1;                    
            elseif strcmp(varargin{i},'value_all')                 
                %ertellt Werte fuer NHA&SHA, zeigt an und speichert sie 
                value_all=1;
            elseif strcmp(varargin{i},'jemeter')
                jemeter=1;
            elseif strcmp(varargin{i},'minus')
                minus=1;
            elseif strcmp(varargin{i},'maxout')
                maxout=varargin {i+1};
            elseif strcmp(varargin{i},'colorm')
                colorm=varargin {i+1};
            elseif strcmp(varargin{i},'fortran')                 
                 %erstellt eine Guess-conforme datei aus den Fortran generierten dateien
                fortran=1;
                fortrangridfile=varargin {i+1};
            elseif strcmp(varargin{i},'degree')
                degree=varargin {i+1};
            elseif strcmp(varargin{i},'fortrangrid')
                fortrangrid=1;
            elseif (strcmp(varargin{i},'africa'))
                africa=1;
           elseif (strcmp(varargin{i},'europe'))
                europe=1;
          elseif (strcmp(varargin{i},'sweden'))
                sweden=1;
            elseif (strcmp(varargin{i},'world'))
                world=1;
            elseif (strcmp(varargin{i},'lonlat'))
                lonlat=1;
                lonlat_borders=varargin {i+1}            
            elseif (strcmp(varargin{i},'canada'))
                canada=1;
             elseif (strcmp(varargin{i},'set_caxis'))
                set_caxis=1;
                caxis_values=varargin {i+1}            
             elseif (strcmp(varargin{i},'maximum'))  
                
                maxwerte=1;
                
            end
        
        end
        %if fileread==0
        %     rengrid=varargin{2};
        %     read_data=0;
        %end
        datai=1;
        if fortran==1;
            %erstelle eine Guess-conforme datei aus den Fortran generierten dateien
            % achtung das Jahr wird immer auf 1000 gesetzt!
            % ziehe
            grid=load (strcat(fortrangridfile,ext));  
            
            grid=(round((grid/100)*4)/4); % LPJ schreibr oft 0.24 anstelle von 0.25!
            grid(:,3)=1000;
            rengrid=load (strcat(filename,ext));
            rengrid=reshape(rengrid,prod(size(rengrid))/size(grid,1),size(grid,1))';
            rengrid=[grid rengrid];
            
            col=4;
            displayyear=1000;
            
        else
            if read_data
                %   try  % versuche ersteinmal die datei als ohne header zu oeffnen
                try
                    rengrid=load (strcat(filename,ext));
                    if fortrangrid
                        rengrid(:,1:2)=(round((rengrid(:,1:2))*4)/4); % LPJ schreibr oft 0.24 anstelle von 0.25!
                        rengrid(:,4:size(rengrid,2)+1)=rengrid(:,3:size(rengrid,2));
                        rengrid(:,3)=1000;
                        %Jahreszahl einfuegen 
                    end
                    % fehlerbehebung....
                    %Teilweise wird dieselbezelle mehrfach gerechnet und ann werden alle Zellen hintereinander geschrieben. 
                    %hier wird dann der Mittelwert daraus ermittelt.
                    %                if size(rengrid (rengrid(:,1)==rengrid(200,1) & rengrid(:,2)==rengrid(200,2) & rengrid(:,3)==rengrid(200,3),:),1)>1
                    %                    'fehler benutze einzelnes run verzeichniss !!'
                    %                    return
                    %                end
                    
                    %rengrid=load ('flux.out');
                    
                catch
                    try 
                        % ohne die erste Zeile
                        rengrid=dlmread(strcat(filename,ext),'',1,0); 
                    catch
                        fid=fopen(strcat(filename,ext));
                        if fid<0
                            if ~isempty(strfind(filename,'lai.out')) | ~isempty(strfind(filename,'flux.out')) | ~isempty(strfind(filename,'cmass.out')) | ~isempty(strfind(filename,'FPC.out'))  % versuche es in den Unterordnern
                                folder=strrep(filename,'lai.out','');
                                folder=strrep(folder,'flux.out','');
                                folder=strrep(folder,'Fpar.out','');
                                folder=strrep(folder,'cmass.out','');
                                dd=dir(folder);
                                maxruns=1;
                                for i=1:size (dd,1)
                                    if ~isempty(strfind(dd(i).name,'run'))
                                        maxruns=max(maxruns,str2num(dd(i).name(4:size(dd(i).name,2))));
                                    end
                                end
                                %folgender part dauert ewig, wird aber nur einmal
                                %ausgefuehrrt
                                eval(['! cp ', folder,'run',num2str(1),'\lai.out   ', folder ,'lai.out -f' ])
                                eval(['! cp ', folder,'run',num2str(1),'\Fpar.out  ', folder ,'Fpar.out -f' ])
                                eval(['! cp ', folder,'run',num2str(1),'\cmass.out ', folder ,'cmass.out -f' ])
                                eval(['! cp ', folder,'run',num2str(1),'\anpp.out  ', folder ,'anpp.out -f' ])
                                eval(['! cp ', folder,'run',num2str(1),'\flux.out  ', folder ,'flux.out -f' ])                                                
                                for i=2:maxruns
                                    eval(['! cat ', folder,'run',num2str(i),'\Fpar.out ',  folder ,'Fpar.out > ', folder ,'Fpartmp.out' ])                            
                                    eval(['! cp ', folder ,'Fpartmp.out ', folder ,'Fpar.out -f ' ])
                                    eval(['! rm ', folder ,'Fpartmp.out ' ])

                                    eval(['! cat ', folder,'run',num2str(i),'\cmass.out ',  folder ,'cmass.out > ', folder ,'cmasstmp.out' ])
                                    eval(['! cp ', folder ,'cmasstmp.out  ', folder ,'cmass.out -f' ])
                                    eval(['! rm ', folder ,'cmasstmp.out  ' ])

                                    eval(['! cat ', folder,'run',num2str(i),'\flux.out ',  folder ,'flux.out > ', folder ,'fluxtmp.out' ])
                                    eval(['! cp ', folder ,'fluxtmp.out  ', folder ,'flux.out -f' ])
                                    eval(['! rm ', folder ,'fluxtmp.out  ' ])

                                    eval(['! cat ', folder,'run',num2str(i),'\anpp.out ',  folder ,'anpp.out > ', folder ,'anpptmp.out' ])
                                    eval(['! cp ', folder ,'anpptmp.out  ', folder ,'anpp.out -f' ])
                                    eval(['! rm ', folder ,'anpptmp.out  ' ])

                                    eval(['! cat ', folder,'run',num2str(i),'\lai.out ',  folder ,'lai.out > ', folder ,'laitmp.out' ])
                                    eval(['! cp ', folder ,'laitmp.out  ', folder ,'lai.out -f' ])                            
                                    eval(['! rm ', folder ,'laitmp.out  ' ])

                                end %i=1:maxruns

                                try %versuche es nocheinmal 
                                    rengrid=load (strcat(filename,ext));
                                catch
                                    ['Kann ' strcat(filename,ext) ' nicht oeffnen']
                                    return
                                end %catch 
                            end% if %~isempty(strfind(filename,'lai.out')) | ~isempty(strfind(filename,'flux.out')) | ~isempty(strfind(filename,'cmass.out')) | ~isempty(strfind(filename,'FPC.out'))  % versuche es in den Unterordnern

                        else %if fid<0
                            length= size(str2num(fgetl(fid)),2); % l�nge der ersten Zeile,
                            fclose all;
                            fid=fopen(strcat(filename,ext));% Dateipointer zuruecksetzen            
                        line=0;
                        while 1 
                            tline=fgetl(fid)     ;              
                            if ~ischar(tline) | size(str2num(tline),2)<4
                                break,
                            else
                                if (size(str2num(tline),2)==length)
                                    line=line+1;
                                    rengrid(line,:)=str2num(tline);
                                else
                                    ['kann ', num2str(line),' nicht lesen',tline ]                                                
                                end
                            end
                            if mod(line,10000)==0
                                tline
                            end

                        end
                        fclose (fid);
                        end %if fid<0
                    end % catch
                end
                else
                    % hier vielleicht einen ueberpruefung ob rengrid richtig
                    % eingelesen wurde
                end
            end % fortran
        maxjahr=max(rengrid(:,3));
        minjahr=min(rengrid(:,3));
               
                if value_all==0
                     if read_data
                         ['Maxjahrmax: ',num2str(max(rengrid(:,3))),' Minjahr ',num2str(min(rengrid(:,3)))]
                         if  ~isempty (strfind(filename,'lai')) |  ~isempty (strfind(filename,'fpc'))
                             if size(rengrid,2)==13
                                 header='Lon   Lat  Year   TrTBE   TrIBE    TrBR   TeTBS   TeIBS    TeNE    TeBE C4grass C3grass   Total;'
                             else
                                 header='Lon   Lat  Year  ';
                                 for ihead=4:size(rengrid,2)-1
                                     header=[header,'  ',strcat(' PFT ',num2str(ihead-3))];
                                 end
                                 header=[header,' Total '];
                                 
                             end
                             
                         elseif ~isempty (strfind(filename,'flux'))
                             %   header='Lon   Lat  Year     Veg    Soil    Fire     Est     NEE     CO2      CO     CH4     VOC     TPM     NOX   C_CO2    C_CO   C_CH4   C_VOC Burn_Jan Burn_Feb Burn_Mar Burn_Apr Burn_Mai Burn_Jun Burn_Jul Burn_Aug Burn_Sep Burn_Oct Burn_Nov Burn_Dec Burn_Tot';
                             if size(rengrid,2)==30  
                                 header='Lon   Lat  Year     Veg    Soil    Fire     Est     NEE     CO2      CO     CH4     VOC     TPM     NOX   M_CO2    M_CO   M_CH4   Burn_Jan Burn_Feb Burn_Mar Burn_Apr Burn_Mai Burn_Jun Burn_Jul Burn_Aug Burn_Sep Burn_Oct Burn_Nov Burn_Dec Burn_Tot';
                             elseif size(rengrid,2)==32
                                 header='Lon   Lat  Year     Veg    Soil    Fire     Est     NEE     CO2      CO     CH4     VOC     TPM     NOX   M_CO2    M_CO   M_CH4   Burn_Jan Burn_Feb Burn_Mar Burn_Apr Burn_Mai Burn_Jun Burn_Jul Burn_Aug Burn_Sep Burn_Oct Burn_Nov Burn_Dec Burn_Tot Mean_age Lai_age';
                             else %33
                                 header='Lon   Lat  Year     Veg    Soil    Fire     Est     NEE     CO2      CO     CH4     VOC     TPM     NOX   M_CO2    M_CO   M_CH4   Burn_Jan Burn_Feb Burn_Mar Burn_Apr Burn_Mai Burn_Jun Burn_Jul Burn_Aug Burn_Sep Burn_Oct Burn_Nov Burn_Dec Burn_Tot Mean_age Lai_age Lai_height';
                             end
                         elseif ~isempty (strfind(filename,'anpp'))
                             header='Lon   Lat  Year   TrTBE   TrIBE    TrBR   TeTBS   TeIBS    TeNE    TeBE C4grass C3grass   Total;'
                         elseif ~isempty (strfind(filename,'cmass'))
                             header='Lon   Lat  Year   TrTBE   TrIBE    TrBR   TeTBS   TeIBS    TeNE    TeBE C4grass C3grass   Total;'
                         else
                             'kein header gefunden'%, return
                             
                         end
                     end
                     
                     if prod(size(displayyear))==1
                         if displayyear==-1
                             displayyear=max(rengrid(:,3));          
                             rengrid(rengrid(:,3)<displayyear,:)=[];
                         elseif displayyear<-1                
                             maxyear=max(rengrid(:,3));                          
                             rengrid(rengrid(:,3)<maxyear+displayyear+1,:)=[];                                
                             
                         else
                             rengrid(rengrid(:,3)~=displayyear,:)=[];
                         end
                     else % dann ist es ine periode inbetween
                         rengrid(rengrid(:,3)<displayyear(1),:)=[];
                         rengrid(rengrid(:,3)>displayyear(2),:)=[];
                         
                     end
                        
                     % hier einwenig verkleinern 
                     if col>0
                         rengrid(:,col+1:size(rengrid,2))=[];
                     end
                         

                    gesammtjahre=max(size(find(rengrid(:,1)==rengrid(1,1) & rengrid(:,2)==rengrid(1,2))));

                    % % Hier wird fuer jedes Jahr eine ebene gemacht
                    try 
                     Jahre=unique(rengrid(:,3));
                     level=1;
                     for j=Jahre'
                         rengrid_temp=rengrid(rengrid(:,3)==j,:);
                         rengrid_temp_out(:,:,level)=reshape(rengrid_temp,1,size(rengrid_temp,1),size(rengrid_temp,2));
                         level=level+1;
                     end
                     if maxwerte==0
                        ttrengrid(1,:,:)=mean(rengrid_temp_out,3); %  Hier wird gemittelt - default
                     else
                         ttrengrid(1,:,:)=max(rengrid_temp_out,[],3); %  Hier wird gemittelt - default
                   
                     end
                     
                     rengrid=ttrengrid;
%                          rengrid=reshape(rengrid,gesammtjahre,size(rengrid,1)/gesammtjahre,size(rengrid,2)); % das ist schnelle Version, die aber nicht immer funktioniert. 
                        
                         
                    catch
                        % was passiert hier?
                        % kick die Gridzelle heraus die nicht funktioniert
                         rengrid(:,size(rengrid,2)+1)=rengrid(:,1)*10000+rengrid(:,2)*10;
                         a=(unique(rengrid(:,size(rengrid,2))));
                         Jahranz=floor(size(rengrid,1)/size(a,1))+1;
                         for z=a' 
                             if size(find(rengrid(:,size(rengrid,2))==z),1)~=Jahranz
                                 % wenn es nicht alle Werte gibt, dann ersetze fehlende Werte durch mittelwert
                                 tempgrid=rengrid(rengrid(:,size(rengrid,2))==z,:);
                                 rengrid(rengrid(:,size(rengrid,2))==z,:)=[];
                                 mittel=mean(tempgrid);
                                  % finde fehlendes Jahr
                                  for ersatzjahr=min(rengrid(:,3)):max(rengrid(:,3))
                                     if isempty (find(tempgrid(:,3)==ersatzjahr ))
                                         rengrid(size(rengrid,1)+1,:)=mittel;
                                         rengrid(size(rengrid,1),3)=ersatzjahr;
                                     else
                                         rengrid(size(rengrid,1)+1,:)=tempgrid((tempgrid(:,3)==ersatzjahr),: );
                                     end
                                 end
                             end
                         end
                         rengrid(:,size(rengrid,2))=[];
                         %save ('flux.out','rengrid','-ASCII');
                         rengrid=reshape(rengrid,gesammtjahre,size(rengrid,1)/gesammtjahre,size(rengrid,2));
                   end

                    % hier werden alle ebenen gemittelt
                  %  hier gibt es noch ein ziemliches Problem
%                   size(rengrid);
%                   [sum(rengrid(1,:,6))];   
                  rengrid=squeeze(mean(rengrid,1));  
%                   [sum(rengrid(:,6))]   ;                   
                    % hier werden di eoutputfluxe auf von pro m*m auf eine
                    % totale
                    % Fl�che gebracht
                    %            [mean(rengrid(rengrid(:,2)>0,4))
                    %            mean(rengrid(rengrid(:,2)<0,4))] mean values npp ohne
                    %            gridcellkorrektur
                    flaeche(:,1:2)=rengrid(:,1:2);
                    %newcelldist ausrechnen
                    lons=sort(unique(rengrid(:,1)));
                    lats=sort(unique(rengrid(:,2)));
                    lonsdist=min(lons (2:size(lons,1))- lons (1:size(lons,1)-1));
                    latsdist=min(lats (2:size(lats,1))- lats (1:size(lats,1)-1));
                    
                    
                    
                    if jemeter==0
                        %hier intelligent den zellenabstand herausfinden
                        %spa�ter einmal
                        
                        %    if ~isempty (strfind(filename,'flux')) | ~isempty (strfind(filename,'prec'))
                            %for i=4:size(rengrid,2) 
                                rengrid(:,4:size(rengrid,2))=rengrid(:,4:size(rengrid,2)).*repmat((3080300000*cos(rengrid(:,2)*0.017453280)),1,size(rengrid,2)-3)*4*latsdist*lonsdist; % fuer ein grad ngrid cell 
                           % end
                            flaeche(:,3)=(3080300000*cos(rengrid(:,2)*0.017453280))*4*latsdist*lonsdist; % fuer ein grad ngrid cell 
                     %   end
                    end
                
%                     'meanvalues npp'
                    %rengrid(rengrid(:,2)>0) 
                     if jemeter==0            
%                               [mean(rengrid(rengrid(:,2)>0,4)*3080300000.*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))/(mean((3080300000*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))))... 
%                           mean(rengrid(rengrid(:,2)<0,4)*3080300000.*cos(rengrid(rengrid(:,2)<0,2)*0.017453280))/(mean((3080300000*cos(rengrid(rengrid(:,2)<0,2)*0.017453280)))) ]
%                       'total sum'
%                          [sum(rengrid(rengrid(:,2)>0,4)*3080300000.*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))... 
%                           sum(rengrid(rengrid(:,2)<0,4)*3080300000.*cos(rengrid(rengrid(:,2)<0,2)*0.017453280)) ] /1000/1000/10000 % das hier sollte eigentlich fuer  ein viertel Grad gelten 
%                    
% %                         [mean(rengrid(rengrid(:,2)>0,4))/(mean((3080300000*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))*4)) ...
% %                          mean(rengrid(rengrid(:,2)<0,4))/(mean((3080300000*cos(rengrid(rengrid(:,2)<0,2)*0.017453280))*4)) ]
% %                %         'prec'
% % %%                        [mean(rengrid(rengrid(:,2)>0,31))/(mean((3080300000*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))*4)) ...
% %  %                        mean(rengrid(rengrid(:,2)<0,31))/(mean((3080300000*cos(rengrid(rengrid(:,2)<0,2)*0.017453280))*4)) ]
%                      else
%                          [mean(rengrid(rengrid(:,2)>0,4)*3080300000.*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))/(mean((3080300000*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))))... 
%                           mean(rengrid(rengrid(:,2)<0,4)*3080300000.*cos(rengrid(rengrid(:,2)<0,2)*0.017453280))/(mean((3080300000*cos(rengrid(rengrid(:,2)<0,2)*0.017453280)))) ]
%                       'total sum'
%                          [sum(rengrid(rengrid(:,2)>0,4)*3080300000.*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))... 
%                           sum(rengrid(rengrid(:,2)<0,4)*3080300000.*cos(rengrid(rengrid(:,2)<0,2)*0.017453280)) ] /1000/1000/10000 % das hier sollte eigentlich fuer  ein viertel Grad gelten 
%                       
%                         'prec'
%                          [mean(rengrid(rengrid(:,2)>0,31)*3080300000.*cos(rengrid(rengrid(:,2)>0,2)*0.017453280))/(mean((3080300000*cos(rengrid(rengrid(:,2)>0,2)*0.017453280)))) ...
%                           mean(rengrid(rengrid(:,2)<0,31)*3080300000.*cos(rengrid(rengrid(:,2)<0,2)*0.017453280))/(mean((3080300000*cos(rengrid(rengrid(:,2)<0,2)*0.017453280)))) ]
                     end
% very quick fix to get a map of the pixelsize: 
                


                headi=1;
                try
                    while ~isempty(header)
                        [head{headi} header]=strtok(header);
                        headi=headi+1;
                    end
                end
                if col==-1
                    try
                        col=menu('Choose a column',head);
                    catch
                        header=num2str([1:size(rengrid,2)]);
                        while ~isempty(header)
                            [head{headi} header]=strtok(header);
                            headi=headi+1;
                        end
                        col=menu('Which column',head);
                    end
                elseif col==0
                    col=[4:headi-2];
                end

        % das erzeugt alles ein ein grad gitter?
        %         rengrid(:,1:2)=(round((rengrid(:,1:2)-offset)*1000));
        %         newcelldist_1000=newcelldist*1000;
        %         plotngrid=rengrid((mod(round(rengrid(:,1)),newcelldist_1000)==0 & mod(round(rengrid(:,2)),newcelldist_1000)==0),:);
        %         plotngrid(:,1:2)=plotngrid(:,1:2)./1000;        

        plotngrid=rengrid;
        totlon =[min(plotngrid(:,1)) max(plotngrid(:,1))];
        totlat =[min(plotngrid(:,2)) max(plotngrid(:,2))];
        % Amokzelle
        % 'largest value'
        % zeile =find(rengrid(:,col)==max(rengrid(:,col)));
        % rengrid(zeile,1:2);
        % rengrid(zeile,col);
        
        plotngrid(:,1)=plotngrid(:,1)/lonsdist;  
        plotngrid(:,2)=plotngrid(:,2)/latsdist;  
        

        %         coorsd(:,1)=plotngrid(:,2);
        %         coorsd(:,2)=plotngrid(:,1);        
        %         fid=fopen('coors.txt','w');
        %         for i=1:size (coorsd,1)
        %             fprintf(fid,strcat(num2str(coorsd(i,:)),'\n'));
        %         end
        %         fclose (fid);
        %        totlon =[min(plotngrid(:,1)) max(plotngrid(:,1))]
        %        totlat =[min(plotngrid(:,2)) max(plotngrid(:,2))]
                plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
                plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
                jahresanz=max(size(find (plotngrid(:,1)==plotngrid(2,1) & plotngrid(:,2)==plotngrid(2,2) )));
                combustion=2;
                if combustion==1                    
                    %         wenn combustion berechnen....
                    %         finde anzahl der Feuer... das wird die
                    %         Jahresanzahl
                    combplotngrid=plotngrid;
                    combplotngrid(combplotngrid(:,31)==-1,31)=1;
                    %summiere nur die -1 werte-> anzahl der Feuer                
                    combfiregrid=full(sparse(combplotngrid(:,1),combplotngrid(:,2),combplotngrid(:,31)));
                    combfiregrid(combfiregrid<1)=1;                    
                    %minwert=1 damit es kein 0/0 gibt
                    %ersetze minus 1 durch 0 und summiere normal, danach wird aber nicht durch Jahresanzahl sondern durch ANzahl der Feuer geteilt.
                    combplotngrid=plotngrid;
                    combplotngrid(combplotngrid(:,col(1))==-1,31)=0;                    
                    newngrid=full(sparse(combplotngrid(:,1),combplotngrid(:,2),combplotngrid(:,31)))./combfiregrid;                    
                else
                    % very quick fix to get a map of the pixelsize: 
                    if pixelsize==1
                        plotngrid(:,col(1))=((3080300000*cos(rengrid(:,2)*0.017453280))*4);
                    end
                    newngrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,col(1))))/jahresanz;
                end
                % hier werden alle addiert problem bei combustion
                for iii=1:maxout
                    'before' 
                    [newngrid(newngrid==max(max(newngrid))) mean(max(newngrid))]
                    newngrid(newngrid==max(max(newngrid)))=mean(max(newngrid));
                end
                if max(size(col))>1
                    for coli=1:max(size(col));
                        newngridalle(coli,:,:)=full(sparse(plotngrid(:,2),plotngrid(:,1),plotngrid(:,col(coli))));
                    end
                    newngrid=newngridalle;
                    if (max(size(col))>1)
                        save ('newngridalle','newngridalle','header');
                    end
                end
                R=[0 latsdist; lonsdist 0;  totlon(1) totlat(1)]; 
                if value_all==0
            %%        ['SH Africa:' num2str(sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))) 'NH Africa:'  num2str(sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))) 'Jahr' num2str(displayyear)]
                    %         figure, pcolor(newngrid(:,1:-round(R(3,2)/R(1,2)))')
             %%       strcat(num2str([sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]/(10^12)), 'Tkg')
 newngrid(isnan(newngrid))=0;
%              if jemeter==0 
%                 
%                  strcat(num2str([sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]/(10^12)*1000), 'Tg')
%                  strcat(num2str([sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]/(10^15)*1000), 'Pg')
%                  strcat(num2str([sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]*1000), 'g')
%        
%                  
%         %pcolor (newngrid(:,1:-round(R(3,2)/R(1,2)))) %zeigt die        %suedhemisph�re
%            %      strcat(num2str([sum(sum(flaeche(flaeche(:,2)<0,3))) sum(sum(flaeche(flaeche(:,2)>0,3))) sum(sum(flaeche(:,3)))]));
% 
%              else
%                  strcat(num2str([sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]), 'g')   
%                  strcat(num2str([sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]/10000), 'km*km*10^4')
%              end
              %%      [sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid)) ] 

                end
        %         seengrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,3)));
        %         seengrid(find(seengrid==0))=NaN;
        %         seengrid(find(~isnan(seengrid)))=0;    
        %        newngrid=newngrid+seengrid;

                %COde zuer erzeugung der LAtitudial diagrams
        %         newngrid(isnan(newngrid))=0;
        %         emissum=sum(newngrid);
        %         figure 
        %         plot(-35.5:1:-35.5+71,emissum/10^9,'r--')
        %         hold on
        %         plot(-35.5:1:-35.5+71,BAsum/10^4,'k')
        %         legend({'Carbon emissions [Tg]','Burned area [10^4km^2]' })
        %         xlabel('latitude')
        %         


                if plot==1
                    figure
                    imagesc(newngrid);
                    colorbar


                end
                if map==1
                 %   figure('Units', 'normalized', 'Position', [0.2, 0.35, 0.6, 0.3])
                 figure
                    box off
                    axesm mercator
                    set (gca,'Visible','off')
                     set(gcf, 'color', [1 1 1])
                    %background white
                    %      figure,mapshow(newngrid',R,'DisplayType','surface')             
                  
                    if world==1
                     % worldmap([-30 -10],[40 50]) 
                     worldmap('world')
                    elseif europe==1
                           worldmap ([33 71],[-12 42] )                           
                    elseif sweden==1
                           borders('sweden')                          
                    elseif canada==1
                           worldmap('canada')
                    elseif africa==1
                          worldmap('africa')
                                africa=1;
                                R(3,1)=R(3,1)-1.5;
                                R(3,2)=R(3,2)-1;
                                R(1:2,1:2)=((R(1:2,1:2)).^2).^(1/2);
                        %        R=[0 1; 1 0;-18 -35.5]
                           
                           
                     elseif lonlat==1;
                            worldmap(lonlat_borders([3 4]),lonlat_borders([1 2]))
                                                        
                    end
                  
                    framem('off')
                     if minus==1
                        newngrid=-newngrid;
                     end
                     if jemeter==0
                         %newngrid=newngrid/10^(6);    
                     end
                     
%                     load Seagrid%, da ist eine Zeile mehr drinne als in MODIS _BA Warum eigentlich achtung das hier ist nur fuer die darstellung!                                              
%                     testseagrid=flipdim(Seagrid',1);
%                     testseagrid=testseagrid(3:74,5:72);
                    
                  
                     %   plotnewngrid=flipdim(flipdim(newngrid,1),2);
                       plotnewngrid=newngrid;
%                    plotnewngrid(testseagrid<0)=NaN;
try    
    R(3,1)=R(3,1)-latsdist;
                         R(3,2)=R(3,2)-lonsdist;
                   
                         R(1:2,1:2)=((R(1:2,1:2)).^2).^(1/2);
                
   	
catch         
              
'fehler'
end
%setze den nuller auf weiss
if     set_caxis==1
                caxis (caxis_values);
end
c=colormap(jet);
c(1,:)=[1 1 1];
colormap(c)
colorbar
                    geoshow (newngrid',R,'DisplayType','texturemap')  % das muss texturemap bleiben
                    set(gcf,'Color',[1,1,1])
                    borders ('countries','color','k')
    if sweden==1
                           borders('sweden')                          
    end              
                    
%if  ~strcmp(version,'7.9.0.529 (R2009b)') & ~strcmp(version,'7.8.0.347 (R2009a)')
   try
   %    geoshow(worldlo('oceanmask'),'EdgeColor','none','FaceColor','w')
   end
%end
%   set(gcf,'Color',[1,1,1])
%   cm=colormap(jet);cm(1,:)=[1 1 1]; colormap (cm);
%                     cm(1,:)=[1 1 1];
%                     colormap (cm);
%                     cm(1,:)=[1 1 1];
%                     colormap (cm);
%                     cm(1,:)=[1 1 1];
%                     colormap (cm);
%                     load Seagrid%, da ist eine Zeile mehr drinne als in MODIS _BA Warum eigentlich achtung das hier ist nur fuer die darstellung!                                              
%                     testseagrid=flipdim(Seagrid',1);
%                     testseagrid=testseagrid(3:74,5:72);
%                     newngrid(testseagrid<0)=NaN;
%                     cm=colormap(jet);
%                     cm(1,:)=[1 1 1];
%                     colormap (cm);
%                     if size(colorm)==[1,1];
% %                         colormap('gray');
% %                         colormap(1-colormap);
%                         load Seagrid%, da ist eine Zeile mehr drinne als in MODIS _BA Warum eigentlich achtung das hier ist nur fuer die darstellung!                                              
%                         Seagrid=flipdim(Seagrid,2);
%                         Seagrid(:,1:3)=[]; 
%                         Seagrid(:,76)=0;
%                         Seagrid(1:74,:)=Seagrid(4:77,:);
%                         newngrid(Seagrid<0)=NaN;
% %                         figure
% %                         pcolor (newngrid')
% %                         shading flat
% %                      
%                           figure
%                     axesm mercator
%                     %      figure,mapshow(newngrid',R,'DisplayType','surface')
%                     worldmap('africa')
%                   
%                                 geoshow (newngrid',R,'DisplayType','surface')
%                         
%                     else
%                         
%                         colormap(colorm);
%                     end


                       %           colormap(1-[0         0         0
%     0.1 0.1 0.1
%           0.2000    0.2000    0.2000
%     0.4000    0.4000    0.4000
%     0.6000    0.6000    0.6000
%     0.8000    0.8000    0.8000
%     1.0000    1.0000    1.0000])
                    colorbar
                end
                if histo==1
                    % histogram of the mothly values, either BA or CO emissions
                    for month =1:12
                        [temp(:,:,month) R]=downscale('read_only','filename',filenme,'column',17+month);
                        histvalue(month)=sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))));
                    end                        
                    figure
                    bar(histvalue);
                    mean(histvalue)
                    std(histvalue)
                    save ('histvalue','histvalue');
                end
            else %value_all==1
                % all values for all years
                for year =minjahr:maxjahr
                    [newngrid R]=downscale('read_only','filename',filename,'column',col,'year',year);
                    histvalue(year-minjahr+1,:)=[sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))-sum(sum(newngrid(:,1:-round(R(3,2)/R(1,2)))))  sum(sum(newngrid))]
                end                        
                save ('histvalue','histvalue');            
        end
        
     
   case 'read_run_only'
        for i=1:nargin
            if strcmp(varargin{i},'column')
                col=varargin{i+1};
                break
            else
                col=-1;
            end
        end
        newcelldist=varargin{2};                
        offset=varargin{3};
        filename=varargin{4};
        ext=varargin{5};
        numberoffiles=varargin{6};
        direc=varargin{7};
        datai=1;
        for filenumber=1:numberoffiles
 %           if numberoffiles==1
                fid=fopen( strcat(strcat(direc,num2str(filenumber)),filename,ext)) ;
                strcat('read file:',strcat(strcat(direc,num2str(filenumber)),filename,ext))
  %          else
   %             fid=fopen(strcat(filename,strcat(num2str(filenumber),ext)))
   %             strcat(filename,strcat(num2str(filenumber),ext))
   %         end
            header=fgetl(fid); %skip header
            while ~feof(fid) 
                line = fgetl(fid);
                
                if datai==1 | size(str2num(line),2)==size(rengrid,2) % das ist um halbfertige Zeilen zu erkennen
                    rengrid(datai,:)=str2num(line);
                    datai=datai+1;
                    
                end
            end
            fclose (fid) ;
        end
        headi=1;
        while ~isempty(header)
            [head{headi} header]=strtok(header);
            headi=headi+1;
        end
        if col==-1
            col=menu('Choose a column',head);
        end
        rengrid(:,1:2)=(round((rengrid(:,1:2)-offset)*1000));    
        newcelldist_1000=newcelldist*1000;
        plotngrid=rengrid(mod(round(rengrid(:,1)),newcelldist_1000)+mod(round(rengrid(:,2)),newcelldist_1000)==0,:);
        plotngrid(:,1:2)=plotngrid(:,1:2)./newcelldist_1000;        
        coorsd=plotngrid(:,1:2);
%         fid=fopen('coors','w');
%         for i=1:size (coorsd,1),fprintf(fid,strcat(num2str(coorsd(i,:)),'\n')),end
%         fclose (fid);
        totlat =[min(plotngrid(:,1)) max(plotngrid(:,1))];
        totlon =[min(plotngrid(:,2)) max(plotngrid(:,2))];        
        plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
        plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
        newngrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,col)));
        seengrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,3)));
        seengrid(find(seengrid==0))=NaN;
        seengrid(find(~isnan(seengrid)))=0;    
        newngrid=newngrid'+seengrid';
        R=[0 newcelldist; newcelldist 0; totlat(1) totlon(1)];         
    case 'read_and_plot_TIN'
        for i=1:nargin
            if strcmp(varargin{i},'column')
                col=varargin{i+1};
                break
            else
                col=-1;
            end
        end
                
        filename=varargin{4};
        newcelldist=varargin{2};
        offset=varargin{3};
        ext=varargin{5};
        numberoffiles=varargin{6};
        datai=1;
        for filenumber=1:numberoffiles
            if numberoffiles==1
                fid=fopen(strcat(filename,ext)) ;
                strcat('read file:',strcat(filename,ext))
            else
                fid=fopen(strcat(filename,strcat(num2str(filenumber),ext)))
                strcat(filename,strcat(num2str(filenumber),ext))
            end
            header=fgetl(fid); %skip header
            while ~feof(fid) 
                line = fgetl(fid);
                
                if datai==1 | size(str2num(line),2)==size(rengrid,2) % das ist um halbfertige Zeilen zu erkennen
                    rengrid(datai,:)=str2num(line);
                    datai=datai+1;
                    
                end
            end
            fclose (fid)                ;
        end
        headi=1;
        while ~isempty(header)
            [head{headi} header]=strtok(header);
            headi=headi+1;
        end
        if col==-1
            col=menu('Choose a column',head);
        end
        newngrid=rengrid;
%         newngrid(:,1:2)=(round((rengrid(:,1:2)-offset)*1000));
%         
        
%        newcelldist=newcelldist*1000;
         scatter(newngrid(:,3),newngrid(:,2),5,newngrid(:,col),'filled');
         colorbar
%         plotngrid=newngrid;
%         plotngrid(:,1:2)=plotngrid(:,1:2)./newcelldist;
%         
%         totlat =[min(plotngrid(:,1)) max(plotngrid(:,1))];
%         totlon =[min(plotngrid(:,2)) max(plotngrid(:,2))];
%         
%         plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
%         plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
%         newngrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,col)));
%         seengrid=full(sparse(plotngrid(:,1),plotngrid(:,2),plotngrid(:,3)));
%         seengrid(find(seengrid==0))=NaN;
%         seengrid(find(~isnan(seengrid)))=0;    
%         newngrid=newngrid'+seengrid';
%         R=[0 newcelldist/1000; newcelldist/1000 0; totlat(1) totlon(1)];


    case 'erzeugewind_und_blitzread'
        
     %for m=1:12, iii=0;if m<10 mon=load (strcat('mon0',num2str(m),'.dat'));, else mon=load (strcat('mon',num2str(m),'.dat'));,end, for i=1:size(mon,1),for ii=1:size(mon,2),iii=iii+1;out(iii)=mon(i,ii);,end,end,pc=reshape(out,144,73)';,pc=flipdim(pc,1);pc(:,145:216)=pc(:,1:72);,pc(:,1:72)=[];winde(:,:,m)=pc;,,end
     %vwind=load('E:\Climate\Wind\vwindday.txt');
     %>> uwind=load('E:\Climate\Wind\uwindday.txt');
 %reuwind=reshape(uwind',3836880,1);
     %pc=reshape(reuwind,144,73,365);
%pc(145:216,:,:)=pc(1:72,:,:);
% pc(1:72,:,:)=[];
%>> pc=flipdim(pc,2);
%>> figure,pcolor(squeeze(double(pc(:,:,1)))'), shading flat
% for i=1:365,outu(:,:,i)=squeeze(double(pc(:,:,i)))';,end
% liest wind.mat, blitz.mat und Africa_05.txt ein und erstellt eine liste :
        % lat,lon,blitz_ja,blitz_feb,..... wind_jan, wind_feb.......
        % das ist ein ziemlcih bescheuertes Format fuer die Umwandlung: 
        % ersteinmal eine Matlab variable erzeugen und dann zusammen mit
        % den Blitzdaten in ein entsprechendes File fuer guess schreiben. 
        % erstellt wird eine Standard output format liste
        wind=load('wind');        
        %dimensionen 73x144x12 also je 2.5 grad (lon,lat,mon), anfang bei
        %-180,-90;
        bl=load('blitze') ;
        % einheit : flashes je km*km und tag
        blitze=bl.blitze;
        %dimensionen : 360   720    12 also je ein halbes gras und (lon,lat,monat)
        %anfang bei -180, -90
        %lod coor 
        coor=load ('Africa_05.txt');
        %[newngrid, R]=downscale('read_only',0.5,0,'Africa_05.txt','',1);
        %newngrid=newngrid'; %nun sind alle gleich orientiert
        newcelldist=varargin{2};                
        offset=varargin{3};
        filename=varargin{4};
        ext=varargin{5};
        direc=varargin{7};
        fid=fopen( strcat(strcat(direc,filename,ext)),'w') ;
        if fid==-1 
            strcat('could not read file:',direc,filename,ext)
            return
        end
        % ersteinmal fuer 0.5 grad: 
        fprintf(fid,'lat    lon flash_jan   flash_feb   flash_mar   flash_apr   flash_mai   flash_jun   flash_jul   flash_aug   flash_sep   flash_okt   flash_nov   flash_dec   wind_jan    wind_feb    wind_mar    wind_apr    wind_mai    wind_jun    wind_jul    wind_aug    wind_sep    wind_okt    wind_nov    wind_dec \n');
        for line=1:size(coor,1)
            latblitz=(coor(line,1)*2)+360;
            lonblitz=(coor(line,2)*2)+180;
            latwind=round(((coor(line,1)*2)+360)/5);
            lonwind=round(((coor(line,2)*2)+180)/5);
            array(1:2)=coor(line,:); % das ist hier um die leerstellen zu erzeugen
            array(3:14)=blitze(lonblitz,latblitz,:); % das ist hier um die leerstellen zu erzeugen
            array(15:26)=wind.wind(lonwind,latwind,:);
            fprintf(fid,strcat(num2str(array),'\n'));
        end
        
        
        
        %for lat=-90: 
        fclose (fid),
    
    
    case 'plot_only'
        ngrid=varargin{1};
        newcelldist=varargin{2};
        offset=varargin{3}; 
        newngrid=(round((ngrid-offset)*10000));
        newcelldist=newcelldist*10000;
        temp=newngrid(abs(mod(round(newngrid(:,2)),newcelldist)+mod(round(newngrid(:,1)),newcelldist))<0.1,:);
        newngrid=temp;
        newngrid(:,3)=1;
        if strcmp(varargin{4},'plot')
            %ngrid vergr�ssern entsprechend der pixelanzahl
            plotngrid=newngrid;
            plotngrid(:,1:2)=plotngrid(:,1:2)./newcelldist;
            %erh�hen und umdrehen /false easting and false northing
            plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
            plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
            j=full(sparse(plotngrid(:,2),plotngrid(:,1),plotngrid(:,3)));
            pcolor(j);
            shading flat;
        end
        
    case 'map_von_schablone'
        

        
        
% schablone
    plusfilename=varargin{8}; % das ist die Koordinatenliste, in diesem fall 0.5
    datafile=varargin{4};     % das sind die Daten in Matrix format, Zeile =Lon, Spalte =Lat, in diesem Fall 0.5 grad
    newcelldist=varargin{2};
    offset=varargin{3};
    ext=varargin{5};
    numberoffiles=varargin{6};% eins
    outputfile=varargin{7};
    datai=1;
    coor=load(strcat(plusfilename,ext));
     max(coor)
    min (coor)
    coor(:,1)=(coor(:,1)+180)*2;
    coor(:,2)=(coor(:,2)+90)*2;
    max(coor)
    min (coor)
    fid=fopen(outputfile,'w');
    for i=1:1%size(datafile,3)
        for ii=1:size(coor,1)
            newngrid(coor(ii,2),coor(ii,1),:)=datafile(coor(ii,2),coor(ii,1),:);
            if newngrid(coor(ii,2),coor(ii,1),:)>0
                fprintf(fid,strcat(num2str([coor(ii,1),coor(ii,2),datafile(coor(ii,2),coor(ii,1),1)]),'\n'));
            else
                fprintf(fid,strcat(num2str([coor(ii,1),coor(ii,2)]),'0.0001 \n'));
            end
        end
    end
    R=1;
    fclose(fid);
%          
%     %umwandeln von Matrix in listenformat
%     load() 
%     
%     
%     
%     
%     
%     [plusngrid Rplus]=downscale('read_only',newcelldist,offset,plusfilename,ext,numberoffiles(1));
%     [minusngrid Rminus]=downscale('read_only',newcelldist,offset,filename,ext,numberoffiles(1));
%     if Rminus(3,2)>Rplus(3,2)
%         lines_to_remove=Rminus(3,2)-Rplus(3,2)       
%         plusngrid(1:lines_to_remove,:)=[];
%         Rplus(3,2)=Rminus(3,2);
%     elseif Rplus(3,2)>Rminus(3,2)
%         lines_to_remove=Rplus(3,2)-Rminus(3,2) 
%         minusngrid(1:lines_to_remove,:)=[];
%         Rminus(3,2)=Rplus(3,2);
%     end
% 
%     if  Rminus(3,1)>Rplus(3,1)
%         rows_to_remove=Rminus(3,1)-Rplus(3,1)
%         plusngrid(:,size(plusngrid,1)-rows_to_remove+1:size(plusngrid,1))=[];
%         Rplus(3,1)=Rminus(3,1);
%         
%     elseif  Rplus(3,1)>Rminus(3,1)
%         rows_to_remove=Rplus(3,1)-Rminus(3,1)
%         minusngrid(:,size(minusngrid,1)-rows_to_remove+1:size(minusngrid,1))=[];
%         Rminus(3,1)=Rplus(3,1);
%     end
%     if size(minusngrid,1)>size(plusngrid,1)
%         lines_to_remove=(size(minusngrid,1)-size(plusngrid,1))
%         minusngrid(:,1:size(minusngrid,1)-rows_to_remove+1)=[];
%     elseif size(plusngrid,1)>size(minusngrid,1)
%         lines_to_remove(size(plusngrid,1)-size(minusngrid,1))
%         plusngrid(:,1:size(plusngrid,1)-rows_to_remove+1)=[];
%     end
%     if size(minusngrid,2)>size(plusngrid,2)
%         rows_to_remove=(size(minusngrid,2)-size(plusngrid,2))
%         minusngrid(:,size(minusngrid,2)-rows_to_remove+1:size(minusngrid,2))=[];
%     elseif size(plusngrid,2)>size(minusngrid,2)
%         rows_to_remove=(size(plusngrid,2)-size(minusngrid,2))
%         plusngrid(:,size(plusngrid,2)-rows_to_remove+1:size(plusngrid,2))=[];
%     end
%     newngrid=plusngrid-minusngrid;
%     R=Rplus;
%     %the upper code is not thouroughly tested!!!    
%     case strcmp('write')
%     case strcmp('read_and_plot')
%     end
%         
%         
        
        
        
    case   'read_and_calc'
    % read and subtract
    plusfilename=varargin{8};
    filename=varargin{4};
    newcelldist=varargin{2};
    offset=varargin{3};
    ext=varargin{5};
    numberoffiles=varargin{6};
    action=varargin{7};
    datai=1;
    [plusngrid Rplus]=downscale('read_only',newcelldist,offset,plusfilename,ext,numberoffiles(1));
    [minusngrid Rminus]=downscale('read_only',newcelldist,offset,filename,ext,numberoffiles(1));
    if Rminus(3,2)>Rplus(3,2)
        lines_to_remove=Rminus(3,2)-Rplus(3,2)       
        plusngrid(1:lines_to_remove,:)=[];
        Rplus(3,2)=Rminus(3,2);
    elseif Rplus(3,2)>Rminus(3,2)
        lines_to_remove=Rplus(3,2)-Rminus(3,2) 
        minusngrid(1:lines_to_remove,:)=[];
        Rminus(3,2)=Rplus(3,2);
    end

    if  Rminus(3,1)>Rplus(3,1)
        rows_to_remove=Rminus(3,1)-Rplus(3,1)
        plusngrid(:,size(plusngrid,1)-rows_to_remove+1:size(plusngrid,1))=[];
        Rplus(3,1)=Rminus(3,1);
        
    elseif  Rplus(3,1)>Rminus(3,1)
        rows_to_remove=Rplus(3,1)-Rminus(3,1)
        minusngrid(:,size(minusngrid,1)-rows_to_remove+1:size(minusngrid,1))=[];
        Rminus(3,1)=Rplus(3,1);
    end
    if size(minusngrid,1)>size(plusngrid,1)
        lines_to_remove=(size(minusngrid,1)-size(plusngrid,1))
        minusngrid(:,1:size(minusngrid,1)-rows_to_remove+1)=[];
    elseif size(plusngrid,1)>size(minusngrid,1)
        lines_to_remove(size(plusngrid,1)-size(minusngrid,1))
        plusngrid(:,1:size(plusngrid,1)-rows_to_remove+1)=[];
    end
    if size(minusngrid,2)>size(plusngrid,2)
        rows_to_remove=(size(minusngrid,2)-size(plusngrid,2))
        minusngrid(:,size(minusngrid,2)-rows_to_remove+1:size(minusngrid,2))=[];
    elseif size(plusngrid,2)>size(minusngrid,2)
        rows_to_remove=(size(plusngrid,2)-size(minusngrid,2))
        plusngrid(:,size(plusngrid,2)-rows_to_remove+1:size(plusngrid,2))=[];
    end
    newngrid=plusngrid-minusngrid;
    R=Rplus;
    %the upper code is not thouroughly tested!!!    
    case 'write'
    case 'read_and_plot'
        filename=varargin{4};
        newcelldist=varargin{2};
        offset=varargin{3};
        ext=varargin{5};
        numberoffiles=varargin{6};
        action=varargin{7};
        datai=1;
        for filenumber=1:numberoffiles
            if numberoffiles==1
                fid=fopen(strcat(filename,ext)) ;
                strcat('read file:',strcat(filename,ext))
            else
                fid=fopen(strcat(filename,strcat(num2str(filenumber),ext)))            
                strcat(filename,strcat(num2str(filenumber),ext))
            end
            header=fgetl(fid); %skip header
            while ~feof(fid) 
                line = fgetl(fid);
                
                if datai==1 | size(str2num(line),2)==size(ngrid,2) % das ist um halbfertige Zeilen zu erkennen
                    ngrid(datai,:)=str2num(line);
                    datai=datai+1;
                    
                end
            end
            fclose (fid)                ;
        end

        headi=1;
        while ~isempty(header)
            [head{headi} header]=strtok(header);
            headi=headi+1;
        end
        col=menu('Choose a column',head);
        newngrid=(round((ngrid-offset)*1000));
        newcelldist=newcelldist*1000;
        temp=newngrid(mod(newngrid(:,2),newcelldist)+mod(newngrid(:,1),newcelldist)==0,:);
        newngrid=temp;
        if strcmp(action,'plot')
            %ngrid vergr�ssern entsprechend der pixelanzahl
            plotngrid=newngrid;
            plotngrid(:,1:2)=plotngrid(:,1:2)./newcelldist;
            %erh�hen und umdrehen /false easting and false northing
            plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
            plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
            j=full(sparse(plotngrid(:,2),plotngrid(:,1),plotngrid(:,col)));
            size(find(j))
            pcolor(j);
            shading flat;
            colorbar;
            
        end
    end
% elseif nargin==4
%     ngrid=varargin{1};
%     newcelldist=varargin{2};
%     offset=varargin{3}; 
%     newngrid=(round((ngrid-offset)*10000));
%     newcelldist=newcelldist*10000;
%     temp=newngrid(abs(mod(round(newngrid(:,2)),newcelldist)+mod(round(newngrid(:,1)),newcelldist))<0.1,:);
%     newngrid=temp;
%     newngrid(:,3)=1;
%     if strcmp(varargin{4},'plot')
%          %ngrid vergr�ssern entsprechend der pixelanzahl
%          plotngrid=newngrid;
%          plotngrid(:,1:2)=plotngrid(:,1:2)./newcelldist;
%          %erh�hen und umdrehen /false easting and false northing
%          plotngrid(:,1)=round(plotngrid(:,1)-min(plotngrid(:,1))+1); %round corrects calculation errors by matlab
%          plotngrid(:,2)=round(plotngrid(:,2)-min(plotngrid(:,2))+1);
%          j=full(sparse(plotngrid(:,2),plotngrid(:,1),plotngrid(:,3)));
%          pcolor(j);
%          shading flat;
%     end
% elseif nargin==7% read and plot
%     downscale
%     
% elseif nargin==6  % nur �bernehmen und abspeichern
%     ngrid=varargin{1};
%     newcelldist=varargin{2};
%     offset=varargin{3};
%     filetowrite=varargin{4};
%     ext=varargin{5};
%     numberoffiles=varargin{6};
%     newngrid=ngrid-offset;
%     temp=newngrid((abs(newngrid(:,2)./newcelldist-fix((newngrid(:,2)./newcelldist)))+...
%         abs(newngrid(:,1)./newcelldist-fix((newngrid(:,1)./newcelldist)))==0),:);
%     newngrid=temp;
%     if numberoffiles>1
%         datapointnr=1;
%         datasteps=fix(size(newngrid,1)/numberoffiles);
%         remains=mod(size(newngrid,1),numberoffiles);
%         for filenumber=1:numberoffiles
%             strcat('write file:',num2str(filenumber))
%             fid=fopen(strcat(filetowrite,strcat(num2str(filenumber),ext)),'w');            
%             for i=datapointnr:datapointnr+datasteps                
%                 fprintf(fid,strcat(num2str(newngrid(i,:)),'\n'));
%             end
%             datapointnr=datapointnr+datasteps;
%             if filenumber==numberoffiles  % beim letzten mal die uebrigbleibenden anh�ngen
%                 for i=datapointnr:size(newngrid,1)
%                     fprintf(fid,strcat(num2str(newngrid(i,:)),'\n'));
%                 end
%             end
%             fclose (fid)                ;
%         end
%     else
%         fid=fopen(filetowrite,'w')
%         for i=1:size(newngrid,1)
%             fprintf(fid,strcat(num2str(newngrid(i,:)),'\n'));
%         end
%     end
%     fclose('all');
% elseif nargin==8% read and subtract
%     plusfilename=varargin{1};
%     filename=varargin{4};
%     newcelldist=varargin{2};
%     offset=varargin{3};
%     ext=varargin{5};
%     numberoffiles=varargin{6};
%     action=varargin{7};
%     datai=1;
%     %plusfile
%     for filenumber=1:numberoffiles(1)
%         if numberoffiles(1)==1
%             fid=fopen(strcat(plusfilename,ext)) ;
%              strcat('read file:',strcat(plusfilename,ext))
%         else           
%             fid=fopen(strcat(plusfilename,strcat(num2str(filenumber),ext)))            
%             strcat(plusfilename,strcat(num2str(filenumber),ext))
%         end
%         headerplus=fgetl(fid); %skip header
%         while ~feof(fid) 
%             line = fgetl(fid);
%                 if datai==1 | size(str2num(line),2)==size(plusngrid,2) % das ist um halbfertige Zeilen zu erkennen
%                     plusngrid(datai,:)=str2num(line);
%                 datai=datai+1;
%                 
%             end
%         end
%         fclose (fid)                ;
%     end
%  
%     
% %minusfile
%     datai=1;
%     for filenumber=1:numberoffiles(2)
%         if numberoffiles(2)==1
%             fid=fopen(strcat(filename,ext)) ;
%              strcat('read file:',strcat(filename,ext))
%         else           
%             fid=fopen(strcat(plusfilename,strcat(num2str(filenumber),ext)))            
%             strcat(filename,strcat(num2str(filenumber),ext))
%         end
%         headerminus=fgetl(fid); %skip header
%         while ~feof(fid) 
%             line = fgetl(fid);             
%             if datai==1 | size(str2num(line),2)==size(minusngrid,2) % das ist um halbfertige Zeilen zu erkennen
%                 minusngrid(datai,:)=str2num(line);
%                 datai=datai+1;
%                 
%             end
%         end
%         fclose (fid)                ;
%     end
%     totlat =[min(min(minusngrid(:,1)),min(plusngrid(:,1))) max(max(minusngrid(:,1)),max(plusngrid(:,1)))];
%     totlon =[min(min(minusngrid(:,2)),min(plusngrid(:,2))) max(max(minusngrid(:,2)),max(plusngrid(:,2)))];
%     %false easting ; false northing
%     plusngrid(:,1)=plusngrid(:,1)-totlat(1)+1;
%     plusngrid(:,2)=plusngrid(:,2)-totlon(1)+1;
%     minusngrid(:,1)=minusngrid(:,1)-totlat(1)+1;
%     minusngrid(:,2)=minusngrid(:,2)-totlon(1)+1;
%     totlat=totlat-totlat(1)+1;
%     totlon=totlon-totlon(1)+1;
%     % und nun subtrahieren
%     headi=1;
%     while ~isempty(headerplus)
%         [headplus{headi} headerplus]=strtok(headerplus);
%         headi=headi+1;
%     end
%     headi=1;
%     while ~isempty(headerminus)
%         [headminus{headi} headerminus]=strtok(headerminus);
%         headi=headi+1;
%     end
%     colplus=menu('Choose a column:plus',headplus);
%     colmin=menu('Choose a column:minus',headminus);
%     plusngrid(:,1:2)=plusngrid(:,1:2)*1000;
%     minusngrid(:,1:2)=minusngrid(:,1:2)*1000;
%     newcelldist=newcelldist*1000;
%     downplusngrid=plusngrid(mod(round(plusngrid(:,2)),newcelldist)+mod(round(plusngrid(:,1)),newcelldist)==0,:);    
%     downminusngrid=minusngrid(mod(round(minusngrid(:,2)),newcelldist)+mod(round(minusngrid(:,1)),newcelldist)==0,:);
%     downplusngrid(:,1:2)=downplusngrid(:,1:2)/newcelldist;
%     downminusngrid(:,1:2)=downminusngrid(:,1:2)/newcelldist;         
%     downresngrid=sparse(downplusngrid(:,1),downplusngrid(:,2),downplusngrid(:,colplus))-sparse(downminusngrid(:,1),downminusngrid(:,2),downminusngrid(:,colmin));
%     seengrid=sparse(downplusngrid(:,1),downplusngrid(:,2),downplusngrid(:,3));% year is always greater zero
%     seengrid(find(seengrid==0))=NaN;
%     seengrid(find(~isnan(seengrid)))=0;
%     if strcmp(action,'plot')
%         pcolor((full(downresngrid)+seengrid)')
%         shading flat;
%         colorbar;
%     end
%     
%     
%     
% else
%     'wrong parameter'
% 
% 
%     


end
    

    
    

    

    
