%eimagexy(epsFile,image,colorMap,x,y,width,height)
% this function write postscript commands in  epsFile to create an image
% written by Stefan Mueller stefan.mueller@fgan.de 1997

function eimagexy(epsFile,image,colorMap,x,y,width,height)
  if (nargin~=7)
    usage('eimagexy(epsFile,image,colorMap,x,y,width,height)');
  end

  [rows cols]=size(image);

  fprintf(epsFile,'/readstring {\n');
  fprintf(epsFile,'currentfile exch readhexstring pop\n');
  fprintf(epsFile,'} bind def\n');
  fprintf(epsFile,'/rpicstr %d string def\n',cols);
  fprintf(epsFile,'/gpicstr %d string def\n',cols);
  fprintf(epsFile,'/bpicstr %d string def\n',cols);
  fprintf(epsFile,'%%%%EndProlog\n');
  fprintf(epsFile,'gsave\n');
  fprintf(epsFile,'%1.2f %1.2f translate\n',x,y);
  fprintf(epsFile,'%1.2f %1.2f scale\n',width,height);
  fprintf(epsFile,'%d %d 8\n',cols,rows);
  fprintf(epsFile,'[ %d 0 0 -%d 0 %d ]\n',cols,rows,rows);
  fprintf(epsFile,'{ rpicstr readstring }\n');
  fprintf(epsFile,'{ gpicstr readstring }\n');
  fprintf(epsFile,'{ bpicstr readstring }\n');
  fprintf(epsFile,'true 3 colorimage\n');
  
  colorMap=fix(colorMap*255);
  for row=1:rows
    colorPart=colorMap(image(row,:),1);
    hexHigh=fix(colorPart/16);
    hexLow=colorPart-hexHigh*16;
    hexAll=[hexHigh';hexLow'];
    hexAll=reshape(hexAll,1,2*cols);
    redRow=sprintf('%x',hexAll);
    colorPart=colorMap(image(row,:),2);
    hexHigh=fix(colorPart/16);
    hexLow=colorPart-hexHigh*16;
    hexAll=[hexHigh';hexLow'];
    hexAll=reshape(hexAll,1,2*cols);
    greenRow=sprintf('%x',hexAll);
    colorPart=colorMap(image(row,:),3);
    hexHigh=fix(colorPart/16);
    hexLow=colorPart-hexHigh*16;
    hexAll=[hexHigh';hexLow'];
    hexAll=reshape(hexAll,1,2*cols);
    blueRow=sprintf('%x',hexAll);
    fprintf(epsFile,'%s\n%s\n%s\n',redRow,greenRow,blueRow);
  end
  fprintf(epsFile,'grestore\n');
