type quality = int
type enhance = bool

type flags = quality * enhance

let string_of_flags (q,e) =
  let qs =
    match q with
    | 2 -> "XX"
    | 1 -> "X"
    | 0 -> ""
    | _ when q >= 3  -> "XXX"
    | _ -> "_"
  in
  let es = if e then "e" else "" in
  qs ^ es
;;

let parse_flags str =
  let str', e = 
    if String.length str - 1 < 0 then str, false
    else begin
      let e = str.[String.length str - 1] = 'e' in
      let str' = if e then String.sub str 0 (String.length str - 1) else str in
      str', e
    end
  in
  let q =
    match str' with
    | "XXX" -> 3
    | "XX" -> 2
    | "X" -> 1
    | "_" -> -1
    | _ -> 0
  in
  q, e
;;

let get_flags file =
  let body, ext = Image.get_extension file in
  try
    let pos = String.rindex body '~' in
    let flag_str = String.sub body (pos+1) (String.length body - (pos+1)) in
    parse_flags flag_str
  with
  | _ -> 0, false
;;
 
let set_flags file flags =
  let body, ext = Image.get_extension file in
  let realbody =
    try
      let pos = String.rindex body '~' in
      String.sub body 0 pos
    with
    | _ -> body
  in
  let flags = string_of_flags flags in
  realbody ^ (if flags = "" then "" else "~" ^ flags) ^ "." ^ ext 
;;
 
