/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/


#ifndef ___ENDIAN_H___
#define ___ENDIAN_H___


typedef union edi {
	int	a;
	char	b[sizeof(int)];
} EDI;

typedef union eds {
	short	a;
	char	b[sizeof(short)];
} EDS;

typedef union edd {
	double	a;
	char	b[sizeof(double)];
} EDD;

typedef union edf {
	float	a;
	char	b[sizeof(float)];
} EDF;

extern char endian_flag;

#define change_endian_s(s)	\
	if ( endian_flag ) {		\
	EDS	ss;			\
	char 	sp;			\
		if ( sizeof(s) != sizeof(short) )	\
			er_panic("change_endian_s(1)");	\
		ss.a = (s);		\
		sp = ss.b[0];		\
		ss.b[0] = ss.b[1];	\
		ss.b[1] = sp;		\
		(s) = ss.a;		\
	}
#define change_endian_i(i)	\
	if ( endian_flag ) {		\
	EDI	ss;			\
	char 	sp;			\
		ss.a = (i);		\
					\
		if ( sizeof(i) != sizeof(int) )		\
			er_panic("change_endian_i(1)");	\
		sp = ss.b[0];		\
		ss.b[0] = ss.b[3];	\
		ss.b[3] = sp;		\
					\
		sp = ss.b[1];		\
		ss.b[1] = ss.b[2];	\
		ss.b[2] = sp;		\
					\
		(i) = ss.a;		\
	}
#define change_endian_d(d)	\
	if ( endian_flag ) {		\
	EDD	ss;			\
	char 	sp;			\
	int	i,j;			\
		ss.a = (d);		\
		i = 0;			\
		j = sizeof(double)-1;	\
		for ( ; i < j ; ) {	\
			sp = ss.b[i];	\
			ss.b[i] = ss.b[j];	\
			ss.b[j] = sp;	\
			i ++;		\
			j --;		\
		}			\
		(d) = ss.a;		\
	}
#define change_endian_f(d)	\
	if ( endian_flag ) {		\
	EDF	ss;			\
	char 	sp;			\
	int	i,j;			\
		ss.a = (d);		\
		i = 0;			\
		j = sizeof(float)-1;	\
		for ( ; i < j ; ) {	\
			sp = ss.b[i];	\
			ss.b[i] = ss.b[j];	\
			ss.b[j] = sp;	\
			i ++;		\
			j --;		\
		}			\
		(d) = ss.a;		\
	}


#endif
