function HeadStr=print_header_fits(InFile,OutFile,SelectedKeys,TableInd,TableName)
%--------------------------------------------------------------------------
% print_header_fits function                                       ImBasic
% Description: Given a FITS image or an header in a 3-column cell array
%              format, convert it to a string array and optionaly print
%              it in a file.
% Input  : - Three columns cell array of header
%            {keyword_name, keyword_val, comment}, where the comment
%            column is optional.
%            Alternatively, this can be a string containing a FITS file
%            name.
%          - String containing name of output file or file identifier.
%            If empty matrix then do not print the header to an output
%            file. Default is empty matrix.
%          - Selected keys to print. If empty matrix then print the entire
%            header. Default is empty matrix.
%          - In case the header data unit is a vector containing several
%            extension, then you can specify the extension name.
%            Default is NaN.
%            This is being used only if the first input parameter is
%            a FITS file.
%          - String containing the name of the header data unit
%            If TableInd is NaN or empty than default is 'PrimaryData',
%            else default is BinaryTable(TableInd).
%            This is being used only if the first input parameter is
%            a FITS file.
% Tested : Matlab 7.10
%     By : Eran O. Ofek                      July 2010
%    URL : http://wise-obs.tau.ac.il/~eran/matlab.html
%--------------------------------------------------------------------------

IdentifyInt = 'y';
EndOfLine   = 'y';

Def.OutFile      = [];
Def.SelectedKeys = [];
Def.TableInd     = NaN;
Def.TableName    = 'PrimaryData';
if (nargin==1),
    OutFile      = Def.OutFile;
    SelectedKeys = Def.SelectedKeys;
    TableInd     = Def.TableInd;
    TableName    = Def.TableName;
elseif (nargin==2),
    SelectedKeys = Def.SelectedKeys;
    TableInd     = Def.TableInd;
    TableName    = Def.TableName;
elseif (nargin==3),
    TableInd     = Def.TableInd;
    TableName    = Def.TableName;
elseif (nargin==4),
    TableName    = Def.TableName;
elseif (nargin==5),
    % do nothing
else
    error('Illegal number of input arguments');
end


if (isstr(InFile)),
   HeaderInfo = get_fits_keyword(InFile,SelectedKeys,TableInd,TableName,'n');
else
   HeaderInfo = InFile;
end

% convert Head to string
[Nline,Nr] = size(HeaderInfo);

HeaderLine = '';
Counter = 0;
for Iline=1:1:Nline
   if (~isempty(HeaderInfo{Iline,1}) && strcmpi(HeaderInfo{Iline,1},'END')==0),
      %--- write keyword name ---
      HeaderLine = sprintf('%-8s',upper(HeaderInfo{Iline,1}));
      switch upper(HeaderInfo{Iline,1})
       case {'COMMENT','HISTORY'}
          % do not write "=" sign
          HeaderLine = sprintf('%s',HeaderLine);
       otherwise
          % write "=" sign
          HeaderLine = sprintf('%s= ',HeaderLine);
      end
      %--- write keyword value ---
      switch upper(HeaderInfo{Iline,1})
       case {'COMMENT','HISTORY'}
          % do not write value
       otherwise
          if (ischar(HeaderInfo{Iline,2})),
             HeaderLine = sprintf('%s''%s''',HeaderLine,HeaderInfo{Iline,2});
             Nblanks    = 20-(length(HeaderInfo{Iline,2})+2);
   
             if (Nblanks<0),
                Nblanks = 0;
             end
             HeaderLine = sprintf('%s%s',HeaderLine,blanks(Nblanks));
         
          elseif (islogical(HeaderInfo{Iline,2}))
  	          switch HeaderInfo{Iline,2}
              case 1
	         HeaderLine = sprintf('%s%20s',HeaderLine,'T');
              case 0
	         HeaderLine = sprintf('%s%20s',HeaderLine,'F');                 
              otherwise
	         error('DataType is not logical');
             end
          elseif (isinteger(HeaderInfo{Iline,2}))
             HeaderLine = sprintf('%s%20i',HeaderLine,HeaderInfo{Iline,2});
          elseif (isfloat(HeaderInfo{Iline,2})),

             switch IdentifyInt
              case 'y'
                 % attempt to identify integers automatically
	             if (fix(HeaderInfo{Iline,2})==HeaderInfo{Iline,2}),
                    % integer identified - print as integer
                    HeaderLine = sprintf('%s%20i',HeaderLine,HeaderInfo{Iline,2});
                 else
                    % float or double
                    HeaderLine = sprintf('%s%20.8f',HeaderLine,HeaderInfo{Iline,2});
                 end
              case 'n'
                   % float or double
                   HeaderLine = sprintf('%s%20.8f',HeaderLine,HeaderInfo{Iline,2});
              otherwise
		             error('Unknown IdentifyInt option');
             end
          else
             error('unknown Format in header information');
          end
      end
      %--- write comment to header ---
      if (Nr>2),
         switch upper(HeaderInfo{Iline,1})
          case {'COMMENT','HISTORY'}
             % do not write "/"
             HeaderLine = sprintf('%s%-s',HeaderLine,HeaderInfo{Iline,3});
          otherwise
             if (isempty(HeaderInfo{Iline,3})),
                % do nothing - do not add comment
             else
                HeaderLine = sprintf('%s /%-s',HeaderLine,HeaderInfo{Iline,3});
             end
          end
      end
       
       % cut line if longer than 80 characters or paded with spaces
       if (length(HeaderLine)>80),
          HeaderLine = HeaderLine(1:80);
       end
       HeaderLine = sprintf('%-80s',HeaderLine);

       %%HeaderBlock = sprintf('%s%s',HeaderBlock,HeaderLine);
       Counter = Counter + 1;
       
       switch lower(EndOfLine)
        case 'y'
           HeaderBlock(Counter,:) = sprintf('%s\n',HeaderLine);
        case 'n'
           HeaderBlock(Counter,:) = sprintf('%s',HeaderLine);
        otherwise
           error('Unknown EndOfLine option');
       end
    end   
end
size(HeaderBlock)

HeadStr = sprintf('%s\n',HeaderBlock.');

if (isempty(OutFile)),
    % do not print output file
else
    if (isstr(OutFile)),
        FID = fopen(OutFile,'w');
    elseif (isnumeric(OutFile)),
        FID = OutFile;  % File is already open
    else
        error('Unknown format for OutFile');
    end
    fprintf(FID,'%s\n',HeaderBlock.');
    if (isstr(OutFile)),
       fclose(FID);
    end
end