## function header=writeheader(sizes,datatype,nbytes,nimage)
## used by edfwrite
## sizes is size(image to be written), cf. Dim_1 and Dim_2
## datatype is string, cf. DataType
## nbytes is number of bytes used for each written element
## nimage is probably number of the image, used for writing multiple images in a single file?
## origin: peter
## 2011-05-18 PC
## * correct error in number of blanks to add to get multiple of 512 bytes header
## * avoid sprintf, use double quotes

function header = writeheader(sizes,datatype,nbytes,nimage,headstruct)

  header = sprintf("%s\n","{");
  header = [header headerstring("HeaderID","EH:000001:000000:000000","string")];
  header = [header headerstring("Image",nimage,"integer")];
  header = [header headerstring("ByteOrder","HighByteFirst","string")];
  header = [header headerstring("DataType",datatype,"string")];
  header = [header headerstring("Dim_1",sizes(1),"integer")];
  header = [header headerstring("Dim_2",sizes(2),"integer")];
  header = [header headerstring("Size",nbytes*sizes(1)*sizes(2),"integer")];
  header = [header headerstring("Date",date,"string")];

  if ((nargin == 5) && (isstruct(headstruct) == 1))
    ## If the structure exists, write the fields to the file
    if (!isempty(headstruct))
      names = fieldnames(headstruct);
      for ii=1:length(names),
        header = [header sprintf("%s",headerstring(names{ii},getfield(headstruct,names{ii}),...
						   class(getfield(headstruct,names{ii}))))];
      endfor
    endif
  endif

  ## Fill to next multiple of 512
  lnspace = mod(length(header)+2, 512);
  if lnspace > 0
    lnspace = 512-lnspace;
  endif
  header = [header blanks(lnspace) "}\n"];
endfunction



