/* DEMO-Program to convert STAD-pictures */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <aes.h>
#include <tos.h>
#include <linea.h>

extern int cdecl fromstad(unsigned char *picstad, unsigned char *pic32k);
extern int cdecl tostad  (unsigned char *pic32k,  unsigned char *picstad);

unsigned char buffer_32k [32000];
unsigned char buffer_stad[32507];

int main(void) {

	char file[FILENAME_MAX]="";
	char path[PATH_MAX]="C:\\*.P?C";
	int  button;
	long length;
	FILE *picture;

	printf("\033E");
	printf("If you select a compressed STAD-pictures *.PAC the file will be loaded,\n");
	printf("uncompressed an saved as an unpacked 32k-picture *.PIC (screenformat)...\n");
	printf("(and vice versa)");
	
	if (fsel_input(path, file, &button))
		if (button == 1) {
			memcpy(strrchr(path, '\\')+1, file, strlen(file));
			if ((picture=fopen(path, "rb")) == NULL) {
				printf("File %s doesn't exists..\n", path);
				exit(-33);
			}
			if (!strcmp(strrchr(path, '\0')-4, ".PAC")) {
				fread(buffer_stad , 1, 32000, picture);
				fclose(picture);
				if (fromstad(buffer_stad, buffer_32k) != 0) {
					printf("Error: this is not a packed STAD-picture\n");
					exit(1);
				}
				memcpy(Physbase(), buffer_32k, 32000);
				path[strlen(path)-2]='I';
				if ((picture=fopen(path, "rb")) != NULL) {
				 	fclose(picture);
				 	if (form_alert(2,
				 	  "[2][ Output-file | already exists..][ Write | Cancel ]")
				 	  == 2)
				 	  exit(2);
				}
				if ((picture=fopen(path, "wb")) == NULL) {
				 	printf("Error: cannot open output-file...\n");
					exit(-36);
				}
				fwrite(buffer_32k, 1, 32000, picture);
				fclose(picture);
			}
			else if (!strcmp(strrchr(path, '\0')-4, ".PIC")) {
				fread(buffer_32k, 32000, 1, picture);
				fclose(picture);
				memcpy(Physbase(), buffer_32k, 32000);
				length=tostad(buffer_32k, buffer_stad);
				path[strlen(path)-2]='A';
				if ((picture=fopen(path, "rb")) != NULL) {
				 	fclose(picture);
				 	if (form_alert(2,
				 	  "[2][ Output-file | already exists...][ Write | Cancel ]")
				 	  == 2)
				 	  exit(2);
				}
				if ((picture=fopen(path, "wb")) == NULL) {
				 	printf("Error: cannot open output-file...\n");
					exit(-36);
				}
				fwrite(buffer_stad, 1, length, picture);
				fclose(picture);
			}
		}

	return(0);
}
