function out = hadamardt(mode,im,errormode,num,spread)
%  Computes Hadamard transforms
%
%  On input:      mode	      mode  1   : regular transform; 
%				   -1   : inverse transform;	
%		  im          mode  1   : image to be transformed 
%				   -1   : transformed image
%		  errormode   errormode   1 : by number of coef's
%			                  2 : by pixel error
%                 num         used for mode 1 only 
%			      errormode   1 : number of desired non-zero coef's
%					  2 : maximum pixel error allowed
%                 spread      tolerance for error (mode 1 only, all errormodes)
%
%  On output:     out         mode  1   : Hadamard transform of im
%			           -1   : Original image 	
%  
%  Calling sequence:
%    
%        out = hadamardt(mode,im,errormode,num,spread)

[m,n] = size(im);

S = hada(m);

if mode==-1			% Return the inverse image 
  out = S'*im*S; 

else

  if errormode==1 		%%%%%%%%%% Number of coef's searching

    imS = S*im*S;

    last = max(max(abs(imS)));
    first = min(min(abs(imS)));

    nz = nonzero(imS);

    if nz < num 
      found = 1;
    else
      found = 0;
    end

    while (~found) & (first <= last) & (abs(num - nz) > spread)

      mid = (first+last) / 2;


      imSclip = clip(imS,mid);
      nz = nonzero(imSclip);

      if num > nz
        last = mid;
      else
        first = mid;
      end

    end
  end

%%%%%%%%%%%%%%%%%%%%%%%%%%% End coef's searching


  if errormode==2           %%%%%%%%%%%%% Pixel error searching

    imS = S*im*S;

    last = max(max(abs(imS)));
    first = min(min(abs(imS)));

    found = 0;
    error = 0;

    imSclip = clip(imS,last-0.000001);
    back = S*imSclip*S;
    error = maxerror(back,im);

    if error<=num
      found = 1;
    else
      imSclip = imS;
      found = 0;
      error = 0;
    end

    while (~found) & (first+0.001 < last) & (abs(error-num) > spread)

      mid = (first+last) / 2;

      imSclip = clip(imS,mid);
      back = S*imSclip*S;
      error = maxerror(back,im);

      if num > error
        first = mid;
      else
        last = mid;
      end

    end

    back = S*imSclip*S;

  end
%%%%%%%%%%%%%%%%%%%%%%%%%%% End Pixel error searching

  out = imSclip;

end







