function [x,map]=imgwrite(x,p1,p2,p3)
% IMGWRITE  Write an image file
%	[x,map]=imgwrite(x,FileName,Format) and 
%	[x,map]=imgwrite(x,map,FileName,Format) use the Matlab function 
%	IMWRITE as backbone to write "any" image file format. 
%	In cases of formats unknown by imwrite, the file is converted 
%	using imconv or other programs.
%	If the parameter Format is not given, the format is determined by
%	the extension of the FileName. See IMWRITE for a description of the 
%	structure of x.
%	
%	See HELP IMGREAD for a list of supported formats.
%	In the cases of JPEG and TIFF, IMWRITE offers greater flexibility.

% "Defines"
WriteDirect=1;
ImConv=2;
HipsWrite=3;

% Parameter list processing
if exist('p2')~=1, p2=[]; end
if exist('p3')~=1, p3=[]; end
if isstr(p1), 
  ColorMap=[]; FileName=p1; Format=p2; 
else
  ColorMap=p1; FileName=p2; Format=p3;
end

if isempty(Format)
  ExtStart=findstr(FileName,'.');
  if isempty(ExtStart)
    error('No extension in file name, can not determine format');
  end
  ExtStart=ExtStart(end)+1;
  Format=FileName(ExtStart:end);
end
Format=lower(Format);

Conversion=0;
switch Format
  case 	'bmp',		Conversion=WriteDirect;
  case	'ncsa',		Conversion=WriteDirect; Format='hdf';
  case	'df',		Conversion=WriteDirect; Format='hdf';
  case  'jpg',		Conversion=WriteDirect;
  case  'jpeg',		Conversion=WriteDirect;
  case  'pcx',		Conversion=WriteDirect;
  case  'pcc',		Conversion=WriteDirect; Format='pcx';
  case  'tif',		Conversion=WriteDirect;
  case  'tiff',		Conversion=WriteDirect;
  case  'xwd',		Conversion=WriteDirect;
  case  'x11',		Conversion=WriteDirect; Format='xwd';
  case  'xbm',		Conversion=WriteDirect; Format='xwd';
  case  'bm',		Conversion=WriteDirect; Format='xwd';
  case  'hips',		Conversion=HipsWrite;
  case  'h',		Conversion=HipsWrite;   Format='hips';
  otherwise,		Conversion=ImConv;
end

switch Conversion
  case WriteDirect,  
    if isempty(ColorMap), 
      imwrite(x,FileName,Format);
    else 
      imwrite(x,ColorMap,FileName,Format); 
    end
  case HipsWrite,    error('HIPS write not yet supported');
  case ImConv,       imconv(x,ColorMap,FileName,Format);
  otherwise,         error('Illegal state. Internal error in imgwrite');
end


% -----------------------------------------------------------------------
function [x,map]=imconv(x,ColorMap,FileName,Format)
% Write an image converted by imconv

% Save to temporary TIFF file and convert
TmpFN=tempnam;
if isempty(ColorMap), 
  imwrite(x,TmpFN,'tiff');
else 
  imwrite(x,ColorMap,TmpFN,'tiff'); 
end
if 0
  % ImTools 1995-edition
  eval(sprintf('!imconv -informat tiff %s -outformat %s %s',...
    TmpFN,Format,FileName));
else
  % ImTools 1992-edition
  eval(sprintf('!imconv -tiff %s -%s %s',...
    TmpFN,Format,FileName));
end
eval(sprintf('!rm %s',TmpFN));

