function export_netCDF(md,filename)	
	
%Now going on Real treatment
	if exist(filename),
		disp(sprintf('File %s allready exist', filename));
		prompt = 'Give a new name or "delete" to replace: ';
		newname = input(prompt,'s');
		if strcmp(newname,'delete')
			delete(filename)
		else
			disp(sprintf('New file name is %s ', newname));
			filename=newname
	  end
  end
	%open file and write description
	mode = netcdf.getConstant('NC_NETCDF4');
	mode = bitor(mode,netcdf.getConstant('NC_NOCLOBBER'));%NOCLOBBER to avoid overwrite
	ncid = netcdf.create(filename,mode);
	netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['Results for run ' md.miscellaneous.name]);
	netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Date',['Created ' datestr(now)]);
	
	%gather geometry and timestepping as dimensions
	Duration=md.timestepping.final_time-md.timestepping.start_time;
	if Duration>0 && md.timestepping.time_step*md.settings.output_frequency>0,
		StepNum=Duration/(md.timestepping.time_step*md.settings.output_frequency);
	else
		StepNum=1;
  end							
 
	%define netcdf dimensions
	DimSize(1).index=netcdf.defDim(ncid,'Dimension1',md.mesh.numberofelements);
	DimSize(2).index=netcdf.defDim(ncid,'Dimension2',md.mesh.numberofvertices);
	DimSize(3).index=netcdf.defDim(ncid,'Dimension3',size(md.mesh.elements,2));
	DimSize(4).index=netcdf.defDim(ncid,'Dimension4',StepNum);
	DimSize(5).index=netcdf.defDim(ncid,'Dimension5',40);
	DimSize(6).index=netcdf.defDim(ncid,'Dimension6',2);
	
	for i=1:length(DimSize),
		[DimSize(i).name,DimSize(i).value]=netcdf.inqDim(ncid,DimSize(i).index);
		DimValue(i)=DimSize(i).value;% putting vallues in an array for
                                 % further use
  end
 
	%Needs a first turn arround for var def
 
	%get all model classes and create respective groups
	groups=fieldnames(md);
	for i=1:length(groups),
		disp(sprintf('group name in tree %s ',groups{i}));
		groupID=netcdf.defGrp(ncid,groups{i});
		%In each group gather the fields of the class
		groupfields=fields(md.(groups{i}));
		%Special treatment for the results
		if strcmp(groups(i),'results'),
			for j=1:length(groupfields)%looping on the differents solutions
				netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype','results');
				subgroupID=netcdf.defGrp(groupID,groupfields{j});
				netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',groupfields{j});
				%disp(sprintf('=====Field name in tree %s ',groupfields{j}));
				if length(md.results.(groupfields{j}))>1,
					%the solution have several timestep get last timesteps and output frequency
					last_step = length(md.results.(groupfields{j}));
					%grab first time step
					subfields=fields(md.results.(groupfields{j})(1));
					for k=1:length(subfields),
						if ~strcmp(subfields(k),'errlog') && ~strcmp(subfields(k),'outlog') && ~strcmp(subfields(k),'SolutionType'),
							%disp(sprintf('==========SubField name in tree %s ',subfields{k}));
							Var=md.results.(groupfields{j})(1).(subfields{k});
							[DimSize,DimValue]=DefCreateVar(ncid,Var,subgroupID,subfields{k},DimSize,DimValue,true,last_step,md,groupfields{j});
			      end
		      end
				elseif length(md.results.(groupfields{j}))==1,
					%only one timestep
					subfields=fields(md.results.(groupfields{j}));
					for k=1:length(subfields),
						%disp(sprintf('==========SubField name in tree %s ',subfields{k}));
						if ~strcmp(subfields(k),'errlog') && ~strcmp(subfields(k),'outlog') && ~strcmp(subfields(k),'SolutionType'),
							Var=md.results.(groupfields{1})(1).(subfields{k});
							[DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,subfields{k},DimSize,DimValue,false);
			      end
		      end
				else
					print 'Result format not suported'
		    end
	    end
		else
			for j=1:length(groupfields),
				disp(sprintf('=====Field name in tree %s ',groupfields{j}));
				netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',class(md.(groups{i})));
				Var=md.(groups{i}).(groupfields{j});
				[DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,groupfields{j},DimSize,DimValue,false);
	    end
	  end	
  end
	netcdf.close(ncid);
end

function [DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,field,DimSize,DimValue,istime,last,md,midfield)
	varclass=class(Var);
	varsize=size(Var);
	varlength=length(Var);
	if isa(Var,'logical'),
		if Var,
			LogicString='True';
		else,
			LogicString='False';
  	end
		netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,LogicString);
	elseif isa(Var,'char'),
		netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,Var);
	elseif isa(Var,'double'), %dealing with arrays
		[dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,field,DimSize,DimValue,istime);
 		varid = netcdf.defVar(groupID,field,'NC_DOUBLE',dims);
		if istime,
			VarTab=Var;
			for i=2:last,
				TimeVar=md.results.(midfield)(i).(field);
				VarTab=[VarTab TimeVar];
	    end
			netcdf.putVar(groupID,varid,VarTab);
		else
			if length(Var)==0,
				netcdf.putVar(groupID,varid,NaN);
			else
				netcdf.putVar(groupID,varid,Var);
	    end
	  end
	elseif isa(Var,'cell'),
		[dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,field,DimSize,DimValue,istime);
		%dirty hack to be able to pass strings
		varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
		if length(Var)==0,
			netcdf.putVar(groupID,varid,0,9,'emptycell')
		else
			for i=1:length(Var),
				startpoint=zeros(size(Var));
				startpoint(:,i)=i-1;
				if length(Var)>1,
					endpoint=[min(length(Var{i}),40) 1];
				else
					endpoint=min(length(Var{i}),40);
		    end
				if length(Var{i})>40,
					netcdf.putVar(groupID,varid,startpoint,endpoint,Var{i}(1:40))
					disp(sprintf('some variable have been truncated'));
			  else
					netcdf.putVar(groupID,varid,startpoint,endpoint,Var{i})
	      end
	    end
	  end
	elseif isa(Var,'struct'),
		%Start by getting the structure fields and size
		locfields=fields(Var);
		[dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,locfields,DimSize,DimValue,istime);
		varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
		if length(locfields)==0,
			netcdf.putVar(groupID,varid,[0,0],[11,1],'emptystruct')
		else
			for i=1:length(locfields),
				for j=1:2,
					if j==1,
						startpoint=[0,0,i-1];
						CharVar=locfields{i};
					else
						startpoint=[0,1,i-1];
						if isa(Var.(locfields{i}),'char'),
							CharVar=Var.(locfields{i});
						else
							CharVar=num2str(Var.(locfields{i}));
			      end
		      end
					endpoint=[min(length(CharVar),40),1,1];
					if length(CharVar)>40,
						netcdf.putVar(groupID,varid,startpoint,endpoint,CharVar(1:40))
						disp(sprintf('some variable have been truncated'));
					else
						netcdf.putVar(groupID,varid,startpoint,endpoint,CharVar)
		      end
		    end
	    end
		end
	else
		disp(sprintf('no support for class %s of field %s',varclass,field));
  end
	return
end

function [dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,field,DimSize,DimValue,istime)
	dims=[];
	%specific treatment for structures
	if isa(Var,'struct')
		varsize=size(field); %we pass here the fields of the current structure
		MatOrVec=varsize>1; %checking if we have a matrix (1 1) or vector (1 0)
		for i=1:sum(MatOrVec), %loop on the number of (non 1) dimensions
			currentdim=varsize(i);
			dimexist=DimValue==currentdim;
			if sum(dimexist)==0, %dimension is new to us, need to create it
				dimname=strcat('Dimension',int2str(length(DimValue)+1));
				dimindex=length(DimSize)+1;
				DimSize(dimindex).index=netcdf.defDim(ncid,dimname,currentdim);
				[DimSize(dimindex).name,DimSize(dimindex).value]=netcdf.inqDim(ncid,DimSize(dimindex).index);
				dims(i)=DimSize(dimindex).index;
				DimValue(dimindex)=currentdim;
			else
				dimindex=find(dimexist);
				if DimSize(dimindex).value~=currentdim,
					error('Indexation problem with the dimension structure')
		    end
	    end
			dims(i)=DimSize(dimindex).index;
	  end
		dims=[DimSize(6).index dims];
	else
		%with a cell array need to grab the transposed size to work
		if isa(Var,'cell'),
			varsize=size(Var');
		else
			varsize=size(Var);
    end
		MatOrVec=varsize>1; %checking if we have a matrix (1 1) or vector (1 0)
		for i=1:sum(MatOrVec), %loop on the number of (non 1) dimensions
			currentdim=varsize(i);
			dimexist=DimValue==currentdim;
			if sum(dimexist)==0, %dimension is new to us, need to create it
				dimname=strcat('Dimension',int2str(length(DimValue)+1));
				dimindex=length(DimSize)+1;
				DimSize(dimindex).index=netcdf.defDim(ncid,dimname,currentdim);
				[DimSize(dimindex).name,DimSize(dimindex).value]=netcdf.inqDim(ncid,DimSize(dimindex).index);
				dims(i)=DimSize(dimindex).index;
				DimValue(dimindex)=currentdim;
			else
				dimindex=find(dimexist);
				if DimSize(dimindex).value~=currentdim,
					error('Indexation problem with the dimension structure')
		    end
	    end
			dims(i)=DimSize(dimindex).index;
    end
  end
	if istime,
		dims=[dims DimSize(4).index];%adding the time dimension if necessary
  end
	%if we have a cell variable we need to add a stringlength dimension 
	if isa(Var,'cell') || isa(Var,'struct'),
		dims=[DimSize(5).index dims]
  end
end
