anchor.diff:      out_mime/2,
       string2filter/2,
       cmd_args/3,
  -    calc_size/7
  +    calc_size/7,
  +
  +    add_optional_quality_1/2
   ]).
   
   -define(MAX_WIDTH,  5000).
   -define(MAX_HEIGHT, 5000).
  +
  +% Low and max image size (in total pixels) for quality 99 and 55.
  +% A small thumbnail needs less compression to keep image quality.
  +-define(PIX_Q99, 1000).
  +-define(PIX_Q50, 250000).
   
   -include_lib("zotonic.hrl").
   
  
positive.code:                 end,
      Filters4 = case is_blurred(Filters3) of
                      true ->  Filters3;
                      false -> case Mime of
                                   "image/gif" -> Filters3;
                                   "image/png" -> Filters3;
                                   _ -> Filters3 ++ [sharpen_small]
                               end
                 end,
      Filters5 = case proplists:get_value(background, Filters4) of
                      undefined -> default_background(OutMime) ++ Filters4;
                      _ -> Filters4
                 end,
  
      {EndWidth,EndHeight,Args} = lists:foldl(fun (Filter, {W,H,Acc}) -> 
                                                  {NewW,NewH,Arg} = filter2arg(Filter, W, H, Filters5),
                                                  {NewW,NewH,[Arg|Acc]} 
                                              end,
                                              {ImageWidth,ImageHeight,[]},
                                              Filters5),
      {EndWidth, EndHeight, lists:reverse(Args)}.
  
  
  
negative.code: is_blurred([{blur, _}|_]) -> true;
  is_blurred([_|Rest]) -> is_blurred(Rest).
  
  is_lossless("image/gif") -> true;
  is_lossless("image/png") -> true;
  is_lossless(_) -> false.
  
  is_enabled(_F, []) -> false;
  is_enabled(F, [F|_]) -> true;
  is_enabled(F, [{F, Val}|_]) -> z_convert:to_bool(Val);
  is_enabled(F, [_|R]) -> is_enabled(F, R).
  
  
  add_optional_quality(Fs, true, _W, _H) ->
      Fs;
  add_optional_quality(Fs, false, W, H) ->
      case proplists:is_defined(quality, Fs) of
          true -> Fs;
          false -> add_optional_quality_1(Fs, W*H)
      end.
  
  add_optional_quality_1(Fs, Pixels) when Pixels =< ?PIX_Q99 ->
      Fs ++ [{quality, 99}];
  add_optional_quality_1(Fs, Pixels) when Pixels >= ?PIX_Q50 ->
      Fs ++ [{quality, 50}];
  add_optional_quality_1(Fs, Pixels) ->
      % Calculate the quality on a lineair scale between PIX_Q50 and PIX_Q99
      Q = 99 - round(50 * (Pixels - ?PIX_Q99) / (?PIX_Q50 - ?PIX_Q99)),
      Fs ++ [{quality, Q}].
  
  %% @spec out_mime(Mime, Options) -> {Mime, Extension}
  %% @doc Return the preferred mime type of the image generated by resizing an image of a certain type and size.
  