
/*****$DEF : *Jérôme Santini*Sta*0.02*1.01* $*
**	___000039		TAB SIZE = 4
**
**               ###
** (c)    ##    ##    1992,93    ##
**       ###   #               ##  ##
**      # ##                  #      #
**        ##   ####   ##  ###   #####    #  ##   ##     ####
**        ##  #   ## ### #     #    ##  ## # ## # ##   #   ##
**        ## ##   #   ###     ##    ## ####  ###  ##  ##   #
**        ## #####    ##      ##    ##  ##   ##   ## ######
**        ## ##    #  ##      ##    #   ##   ##   ### ##    #
**        ##  #####   ##       #####    ##   ##   ##   #####
**        ##
**        ##       ######                              #              #
**        #       #      #                            #              #
**       #       ##                             #
**  #####        ##          #####    #  ##    ##     ##    #  ##    ##
**               ###        #   ##   ## # ##  #####  ###   ## # ##  ###
**                ###      ##   ##  ####  ##   ##     ##  ####  ##   ##
**                  ###    ##  ### # ##   ## # ##   # ## # ##   ## # ## #
**                    ###  ## # ###  ##   ###  ##  #  ###  ##   ###  ###
**                     ###  ##   #   ##   ##    ###   ##   ##   ##   ##
**                      ##
**                      ##
**               #      #  	$Author : Jérôme Santini $
**                ######  	$Creation : 27/12/1992 22:20:51 $
**                        	$Locker : Jérôme Santini $
**                        	$Date : 31/01/1993 12:53:58 $
**
**	$Source : WorkBench:System/Sources/CData/CS/P2T/P2T.c $
**	$Release : 1.01 $
**	$Revision : 0.02 $
**	$State : Sta $
**	$Translator : SAS/C V6.00 $
**
**	$Description :
**
**		P2T : (P)icture to (T)ext.
**
**  P2T Crée des fichier textes à partir d'image ILBM,ou de fontes amiga, pour
** faire  joli  ds  les  fichiers  sources:   un  pixel <=> un char.  C'est ce
** programme qui a été utilisé pour l'entête de ce fichier.
**
**     Requiert jess.lib, iff.lib V22 et KS2.0.
**
**	---------------------------------------------------------------------
**
**	Demonstration rapide : p2t -F Hello world!
**
**	---------------------------------------------------------------------
**
** p2t -? donne :
**
Pic2Txt v1.01ß (c) Jérôme Santini 1992,93 (Jan 31 1993)

Usage : WorkBench:System/Sources/CData/CS/P2T/p2t opts Args

		Where <opts> can be :
-cXX : Comments.
-fXX : Font name: "name/size".
-F   : Use default font.\n\
-n   : do not suppress space at EOL.
-pXX : pattern.
**
**	- l'option -c ajoute un commentaire en début de ligne.
** ex : -c REM ou -c ' ** '
**
**  - l'option -f indique qu'on veut utiliser une fonte amiga plutôt qu'une
** image  ilbm.   les arguments ne sont plus des nom de fichier mais le texte
** à dessiner. ex : -f topaz.font/8
**
**  -  L'option  -F  à le même rôle que -f, mais on utilise la police de la
** fenêtre CLI, ou Topaz/8.
**
**
**	- l'option -p permet de choisir les 'couleurs' :
** ex : -p ' -+*' pour faire un dégradé
**
**	- l'option -n supprime la suppression (!) des blancs en fin de ligne.
**
**	---------------------------------------------------------------------
**
**	Jérôme Santini
**	123 rue d'Entraigues
**	37000 TOURS.
**	FRANCE
**
**  $
**
**	$Log : P2T.c $
** Revision 0.02 31/01/1993 12:53:58 Jérôme Santini Sta ( SAS/C V6.00 )
** 	Option -f ajoutée.
**
** Revision 0.01 27/12/1992 22:20:51 Jérôme Santini Tst ( SAS/C V6.00 )
** 	***    Creation ...   ***
**	Nouvelle version completement ré-écrite.
**
*******************************************************************************/

static char     Pic2Txt_id[] = "$Id : P2T.c           0.002 31/01/1993 12:53:58 Jérôme Santini / Jérôme Santini Sta $";
static char     Pic2Txt_cp[] = "$Compiled: " __FILE__ "\t" __DATE__ " / " __TIME__ " (___000039) $";

/*============================================================================

 	INCLUDES ...

  ============================================================================*/

#include "P2T.h"

/*============================================================================

 	DEFINES / PROTOS ...

  ============================================================================*/

#ifndef MEMF_CLEAR
#define MEMF_CLEAR   (1L<<16)	/* AllocMem: NULL out area before return */
#endif

/* Distance, avec l'option -f, entre les bords et l'image */
#define FOFFSET	2

/*============================================================================

 	VARIABLES GLOBALES ...

  ============================================================================*/

struct OptArg   arg =
{
	"c:p:nh?f:F",
	0,
	0,
	TRUE,
};

extern char     CopyRight[];

struct JessBase *JessBase;
struct Library *IFFBase;
struct Library *DiskfontBase;
struct TextFont *tf;
struct GfxBase *GfxBase;
struct BitMap   bitmap;
extern struct ExecBase *SysBase ;

char            pattern[256] = " #-*&|/0abcdefghijklmnopqrstuvwx #-X&|/0abcdefghijklmnopqrstuvwx";

#define MAXREM	20
char            comment[MAXREM + 1];
char           *fontname = NULL;
int             font;
BPTR            err;	/* stderr */
int             nospace = TRUE;

/*============================================================================

 	CODE ...

  ============================================================================*/

void 
warning(char   *txt)
{
	if (err)
		FPrintf(err, "P2T : %s\n", txt);
}

void
freebitmap(struct BitMap *bit, short depth, short x, short y)
{
	int             size = RASSIZE(x, y) * depth;

	if (bit->Planes[0])
		FreeMem(bit->Planes[0], size);
}

struct BitMap  *
allocbitmap(short depth, short x, short y)
{
	struct BitMap  *bit = &bitmap;
	int             i,
	                size;

	InitBitMap(bit, depth, x, y);

	size = RASSIZE(x, y);

	if (bit->Planes[0] = AllocMem(size * depth, MEMF_CLEAR|MEMF_CHIP))
	{
		for (i = 1; i < depth; i++)
			bit->Planes[i] = bit->Planes[i - 1] + size;
	}
	if (bit->Planes[0] == NULL)
	{
		freebitmap(&bitmap, depth, x, y);
		warning("Can't allocate bitmap.");
	}
	return (bit);
}

int 
Convert(struct RastPort *rp, int w, int h)
{
	int             ret = 20,
	                i,
	                j;
	char           *buff;

	if (buff = AllocMem(w + 1, MEMF_CLEAR))
	{
		*buff = 0;
		for (i = 0; i < h; i++)
		{
			for (j = 0; j < w; j++)		/* crée une nouvelle ligne */
				buff[j] = pattern[ReadPixel(rp, j, i)];

			if (nospace)
			{
				/* Supprimer les blanc en fin de lignes */
				for (; j > 0 && buff[j - 1] == ' '; j--) ;
				buff[j] = 0;
			}
			Printf("%s%s\n", comment, buff);
		}
		FreeMem(buff, w + 1);
		ret = 0;
	} else
		warning("Can't allocate output buffer.");
	return (ret);
}

int
SaveTxt(char   *name, struct IFFL_BMHD *bmhd, IFFL_HANDLE iff)
{
	struct BitMap  *bit;
	struct RastPort rp;
	int             w,l,
	                h,
	                ret = 20;

	if (err && bmhd && iff)
		FPrintf(err, "%s : %ldx%ldx%ld\n", name, bmhd->w, bmhd->h, bmhd->nPlanes);

	if (bmhd && iff)	/* Convertion iff => texte */
	{
		w = bmhd->w;
		h = bmhd->h;
		if (bit = allocbitmap(bmhd->nPlanes, w, h))
		{
			InitRastPort(&rp);
			rp.BitMap = bit;
			IFFL_DecodePic(iff, bit);
			ret = Convert(&rp, w, h);
			freebitmap(bit, bmhd->nPlanes, w, h);
		}
	}else{	/* convertion text => text !!! */

		InitRastPort(&rp);
		SetFont(&rp,tf);

		/* de quelle taille avons nous besoin ? 1eme aproximation */
		h = tf->tf_YSize + 2*FOFFSET ;
		l=strlen(name);
		w = TextLength(&rp,name,l) + 2*FOFFSET ;

		if (bit = allocbitmap(2, w, h))
		{
			rp.BitMap = bit;
			SetAPen(&rp,1);
			Move((&rp),FOFFSET,tf->tf_Baseline+FOFFSET);
			Text(&rp,name,l);
			ret = Convert(&rp, w, h);
			freebitmap(bit,2, w, h);
		}
	}
	return (ret);
}

void
main(int argc, char **argv)
{
	IFFL_HANDLE     iff;
	struct IFFL_BMHD *bmhd;
	struct TextAttr ta;
	struct Window   *win ;
	int             ret = 20,
	                usage = FALSE;
	char            c,
	               *file;
	LONG            l;

	if (argc == 0)
		exit(20);

	if (OPENJESS(0) == 0)
	{
		PutStr("Je ne peux ouvrir jess.library\n");
		exit(20);
	}
	while ((c = GetOpt(argc, argv, &arg)) != EOF)
	{
		switch (c)
		{
			case 'c':
				if (l = strlen(arg.optarg) >= MAXREM)
					arg.optarg[MAXREM] = 0;
				strcpy(comment, arg.optarg);
				break;

			case 'p':
				memcpy(pattern, arg.optarg, strlen(arg.optarg));
				break;

			case 'n':
				nospace = FALSE;
				break;

			case 'f':
				fontname = strdup(arg.optarg);
				font = TRUE;
				break;

			case 'F': /* utiliser la police du CLI */
				win  = (struct Window *)((struct Process *)SysBase->ThisTask)->pr_WindowPtr;
				if ((win) && (win != ((struct Window *)0xFFFFFFFF) ))
					tf = win->RPort->Font ;
				else
					fontname = "topaz.font/9";
				font = TRUE;
				break;

			case 'h':
			default:
				usage = TRUE;
				break;
		}
	}

	CLOSEJESS();

	if (usage || arg.optind >= argc)
	{
		Printf("%s\n\nUsage : %s opts Args\n\n", CopyRight, argv[0]);
		PutStr("\t\tWhere <opts> can be :\n\
-cXX : Comments.\n\
-fXX : Font name: \"name/size\".\n\
-F   : Use default font.\n\
-n   : do not suppress space at EOL.\n\
-pXX : pattern.\n\
");
		exit(1);
	}
	err = Open("*", MODE_OLDFILE);

	warning(CopyRight);

	if (font && fontname)
	{
		char           *ptr,*p;

		OPENDISKFONT(0);
		if (ptr = strchr(fontname, '/'))
		{
			*ptr++ = 0;
			ta.ta_Style = FS_NORMAL;
			ta.ta_Flags = NULL;

			if(strstr(fontname,".font")==NULL)
			{
				p=calloc(strlen(fontname)+6,sizeof(char));
				strcpy(p,fontname);
				strcat(p,".font");
				fontname = p ;
			}
			ta.ta_Name = fontname;
			if (StrToLong(ptr, &l))
			{
				ta.ta_YSize = l;
				tf = OpenDiskFont(&ta);
			}
			if (tf == NULL && err)
				FPrintf(err, "%s/%ld not found\n", fontname, ta.ta_YSize);
		}
	} else
		OPENIFF(22);

	if ((IFFBase || tf) && OPENGFX(37))
	{
		ret = NULL;
		while ((arg.optind < argc) && (ret == NULL))
		{
			file = argv[arg.optind++];
			if (font)
				ret = SaveTxt(file, NULL, NULL);
			else if (iff = IFFL_OpenIFF(file, IFFL_MODE_READ))
			{
				if (bmhd = IFFL_GetBMHD(iff))
					ret = SaveTxt(file, bmhd, iff);
				else if (err)
					FPrintf(err, "%s is not an ilbm pic\n", file);

				IFFL_CloseIFF(iff);
			} else
			{
				if (err)
					FPrintf(err, "Can't open iff file %s\n", file);
			}
		}
	} else
	{
		warning("No font or no iff or diskfont or icon lib");
	}

	if (err)
		Close(err);

	if (tf && fontname)
		CloseFont(tf);
	CLOSEIFF();
	CLOSEGFX();
	CLOSEDISKFONT();
	exit(ret);
}
