/*  Xlunzip - Test tool for the lzip_decompress linux module
    Copyright (C) 2016-2020 Antonio Diaz Diaz.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef max
  #define max(x,y) ((x) >= (y) ? (x) : (y))
#endif
#ifndef min
  #define min(x,y) ((x) <= (y) ? (x) : (y))
#endif

enum {
  min_dictionary_bits = 12,
  min_dictionary_size = 1 << min_dictionary_bits,	/* >= modeled_distances */
  max_dictionary_bits = 29,
  max_dictionary_size = 1 << max_dictionary_bits,
  min_member_size = 36 };


struct Pretty_print
  {
  const char * name;
  char * padded_name;
  const char * stdin_name;
  unsigned longest_name;
  bool first_post;
  };


static const uint8_t lzip_magic[4] = { 0x4C, 0x5A, 0x49, 0x50 }; /* "LZIP" */

typedef uint8_t Lzip_header[6];		/* 0-3 magic bytes */
					/*   4 version */
					/*   5 coded dictionary size */
enum { Lh_size = 6 };

static inline bool Lh_verify_magic( const Lzip_header data )
  { return ( memcmp( data, lzip_magic, 4 ) == 0 ); }

static inline bool Lh_verify_version( const Lzip_header data )
  { return ( data[4] == 1 ); }


typedef uint8_t Lzip_trailer[20];
			/*  0-3  CRC32 of the uncompressed data */
			/*  4-11 size of the uncompressed data */
			/* 12-19 member size including header and trailer */
enum { Lt_size = 20 };

static inline unsigned long long Lt_get_data_size( const Lzip_trailer data )
  {
  unsigned long long tmp = 0;
  int i; for( i = 11; i >= 4; --i ) { tmp <<= 8; tmp += data[i]; }
  return tmp;
  }

static inline unsigned long long Lt_get_member_size( const Lzip_trailer data )
  {
  unsigned long long tmp = 0;
  int i; for( i = 19; i >= 12; --i ) { tmp <<= 8; tmp += data[i]; }
  return tmp;
  }


/* defined in in_place.c */
int decompress_in_place( const int infd, struct Pretty_print * const pp,
                         const bool testing );

/* defined in main.c */
int convert_retval( const int retval );
long flush( void * buf, unsigned long size );
void show_results( struct Pretty_print * const pp, const long in_pos,
                   const long out_pos, const bool testing );
void show_file_error( const char * const filename, const char * const msg,
                      const int errcode );
