File: vdcomp.c

package info (click to toggle)
xv 3.10a-16
  • links: PTS
  • area: non-free
  • in suites: hamm
  • size: 7,836 kB
  • ctags: 3,378
  • sloc: ansic: 42,181; makefile: 152; sh: 78; csh: 37
file content (1471 lines) | stat: -rw-r--r-- 56,661 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
/********************************************************************/
/*  Image Decompression Program - C Version for PC, VAX, Unix       */
/*  and Macintosh systems.                                          */
/*                                                                  */
/*  Decompresses images using Kris Becker's subroutine DECOMP.C     */
/*  which is included in this program in a shortened version.       */
/*                                                                  */
/*  Reads a variable length compressed PDS image and outputs a      */
/*  fixed length uncompressed image file in PDS format with         */
/*  labels, image histogram, engineering table, line header table   */
/*  and an image with PDS, FITS, VICAR or no labels.  If used on    */
/*  a non-byte-swapped machine the image histogram is un-swapped.   */
/*                                                                  */
/********************************************************************/
/*                                                                  */
/*  Use the following commands to compile and link to produce an    */
/*  executable file:                                                */
/*                                                                  */
/*  On an IBM PC (using Microsoft C Version 5.x)                    */
/*                                                                  */
/*    cl /c vdcomp.c                                                */
/*    link  vdcomp/stack:10000;                                     */
/*                                                                  */
/*  On a VAX:                                                       */
/*                                                                  */
/*    cc   vdcomp                                                   */
/*    $define lnk$library sys$library:vaxcrtl.olb                   */
/*    link vdcomp                                                   */
/*                                                                  */
/*  On a Unix host (Sun, Masscomp)                                  */
/*                                                                  */
/*    cc -o vdcomp vdcomp.c                                         */
/*                                                                  */
/*  On a Macintosh (using Lightspeed C)                             */
/*                                                                  */
/*    link with the following libraries:                            */
/*    stdio, storage, strings, unix and MacTraps, with MacTraps     */
/*    and vdcomp in a separate segment.                             */
/*                                                                  */
/********************************************************************/
/*                                                                  */
/*  Use the following command to run the program:                   */
/*                                                                  */
/*    VDCOMP [infile] [outfile] [output format]                     */
/*                                                                  */
/*       infile        - name of compressed image file.             */
/*       outfile       - name of uncompressed output file.          */
/*       output format - selected from the following list:          */
/*                                                                  */
/*          1  SFDU/PDS format [DEFAULT].                           */
/*          2  FITS format.                                         */
/*          3  VICAR format.                                        */
/*          4  Unlabelled binary array.                             */
/*                                                                  */
/*  On the VAX computer you will need to 'install' the program to   */
/*  be able to use command line arguments using the following       */
/*  command:                                                        */
/*                                                                  */
/*  $ vdcomp :== $DISKNAME:[DIRECTORY]vdcomp.exe                    */
/*                                                                  */
/*  where DISKNAME is the disk drive and DIRECTORY is the           */
/*  directory where VDCOMP.EXE is stored.                           */
/*                                                                  */
/********************************************************************/
/*                                                                  */
/* LIMS                                                             */
/*  This program has been tested on a VAX 780 (VMS 4.6), SUN        */
/*  Workstation (UNIX 4.2, release 3.4), an IBM PC                  */
/*  (MICROSOFT 5.1 compiler) and Macintosh IIx using Lightspeed C   */
/*  version 3.0.  When converting to other systems, check for       */
/*  portability conflicts.                                          */
/*                                                                  */
/* HIST                                                             */
/*  bradley@cis.upenn.edu 06-23-94 ansi-fied program                */
/*  datri@convex.com, 11-15-91 added recognition of - as stdout for */
/*  	output filename; disabled various messages; directed        */
/*	messages to stderr; added exit status			    */
/*  DEC89 Modified program to handle both Voyager and Viking images.*/
/*  OCT89 Converted Voyager decompression program to handle Viking  */
/*  compressed images.  Changed obuf to 'unsigned' to simplify      */
/*  computation of checksum.                                        */
/*  AUG89 Added code to get command line arguments for filenames    */
/*  and output format; routines to free memory used by the Huffman  */
/*  tree); fixed the SFDU label output length; and modified the     */
/*  I/O routines so that the open for Host type 2 uses binary I/O.  */
/*  JUN89 Fixed READVAR, to get length on 16-bit unswapped hosts.   */
/*  JUL88 C driver to decompress standard Voyager Compressed images */
/*  by Mike Martin 1989/12/02                                       */
/*                                                                  */
/*  Inputs   - Input file to be decompressed.                       */
/*                                                                  */
/*  Outputs  - Output file containing decompressed image.           */
/*                                                                  */
/********************************************************************/

#include <stdio.h>
#include <stdlib.h>

/* include a malloc.h, of some sort... */
#ifndef VMS   /* VMS hates multi-line '#if's */
# if !defined(ibm032)                    && \
     !defined(__convex__)                && \
     !(defined(vax) && !defined(ultrix)) && \
     !defined(mips)                      && \
     !defined(apollo)                    && \
     !defined(pyr)                       && \
     !defined(__UMAXV__)                 && \
     !defined(bsd43)                     && \
     !defined(aux)                       && \
     !defined(__bsdi__)                  && \
     !defined(sequent)

#  if defined(hp300) || defined(hp800) || defined(NeXT)
#   include <sys/malloc.h>                /* it's in 'sys' on HPs and NeXT */
#  else
#   include <malloc.h>
#  endif
# endif
#endif /* !VMS */


#include <X11/Xos.h>

#define TRUE                  1
#define FALSE                 0

                                    /* pc i/o defines               */
#define O_BINARY         0x8000     /* file mode is binary          */

                                    /* vax i/o defines              */
#define RECORD_TYPE      "rfm=fix"  /* VAX fixed length output      */
#define CTX              "ctx=bin"  /* no translation of \n         */
#define FOP          "fop=cif,sup"  /* file processing ops          */

typedef struct leaf { struct leaf *right;
		      short  int   dn;
		      struct leaf *left;
		    } NODE;

/*************************************************************************
 Declare the tree pointer. This pointer will hold the root of the tree
 once the tree is created by the accompanying routine huff_tree.
**************************************************************************/

  NODE *tree;

/* subroutine definitions                                           */

#undef PARM
#ifdef __STDC__
#  define PARM(a) a
#else
#  define PARM(a) ()
#endif

int  main         PARM((int, char **));
void pds_labels   PARM((int));
void fits_labels  PARM((int));
void vicar_labels PARM((int));
void no_labels    PARM((int));
int  check_host   PARM((void));
int  get_files    PARM((int));
void open_files   PARM((int *));
int swap_int      PARM((int));
void decompress   PARM((char *, char *, int *, int *));
void decmpinit    PARM((int *));
int  read_var     PARM((char *, int));
NODE *huff_tree   PARM((int *));
NODE *new_node    PARM((int));
void sort_freq    PARM((int *, NODE **, int));
void dcmprs       PARM((char *, char *, int *, int *, NODE *));
void free_tree    PARM((int *));
int  free_node    PARM((NODE *, int));

/* global variables                                                 */

#define BUFSIZE 1024
int                infile;
FILE               *outfile;
char               inname[BUFSIZE],outname[BUFSIZE];
int                output_format;
int                record_bytes, max_lines;
int                line_samples, fits_pad;
int               label_checksum = 0L, checksum = 0L;


/*************************************************/
int main(argc,argv)
     int  argc;
     char **argv;
{
  unsigned char ibuf[2048],obuf[2048];
  unsigned char blank=32;
  short         host,length,total_bytes,line,i;
  int          x,hist[511];
  int           count, int_length;

  /*********************************************************************/
  /*                                                                   */
  /* get host information and input and output files                   */
  /*                                                                   */
  /*********************************************************************/

  strcpy(inname,"   ");  
  strcpy(outname,"   ");
  output_format = 0;

  if (argc == 1);                     /* prompt user for parameters */
  else if (argc == 2 && (strncmp(argv[1],"help",(size_t) 4) == 0 || 
			 strncmp(argv[1],"HELP",(size_t) 4) == 0 ||
			 strncmp(argv[1],"?",   (size_t) 1) == 0)) {
    fprintf(stderr,
	    "PDS Image Decompression Program.  Command line format:\n\n");
    fprintf(stderr,"VDCOMP [infile] [outfile] [format code]\n");
    fprintf(stderr,"   infile        - name of compressed image file. \n");
    fprintf(stderr,"   outfile       - name of uncompressed output file.\n");
    fprintf(stderr,"   output format - selected from the following list:\n");
    fprintf(stderr,"\n");   
    fprintf(stderr,"     1  SFDU/PDS format [DEFAULT].\n");   
    fprintf(stderr,"     2  FITS format.              \n");   
    fprintf(stderr,"     3  VICAR format.             \n");   
    fprintf(stderr,"     4  Unlabelled binary array.  \n\n");   
    exit(1);
  }  
  else {
    strncpy(inname,argv[1],BUFSIZE);  
    if (argc >= 3) strncpy(outname,argv[2],BUFSIZE); 
    if (argc == 3) output_format = 1;
    if (argc == 4) sscanf(argv[3],"%d",&output_format); 
  }

  host = check_host();
  host = get_files(host); /* may change host if VAX */

  /*********************************************************************/
  /*                                                                   */
  /* read and edit compressed file labels                              */
  /*                                                                   */
  /*********************************************************************/

  switch (output_format) {
    case 1: pds_labels(host);    break;
    case 2: fits_labels(host);   break;
    case 3: vicar_labels(host);  break;
    case 4: no_labels(host);     break;
  }

  if (record_bytes == 836) {  /* set up values for image sizes */ 
    max_lines    =  800;
    fits_pad     = 2240;
    line_samples =  800;
  }
  else {
    max_lines    = 1056;         
    fits_pad     = 1536;
    line_samples = 1204;
  }

  /*********************************************************************/
  /*                                                                   */
  /* process the image histogram                                       */
  /*                                                                   */
  /*********************************************************************/

  /* need to know record_bytes,hist_count,hist_item_type,item_count.*/
  total_bytes = 0;
  length = read_var((char *)hist,host);
  total_bytes = total_bytes + length;

  if (record_bytes == 836) {  /* read one more time for Voyager image */
    length = read_var((char *)hist+record_bytes,host);
    total_bytes = total_bytes + length;
  }

  if (host == 2 || host == 5)             /* If non-byte swapped    */
    for (i=0; i<256; i++)                 /* host, swap bytes in    */
      hist[i] = swap_int(hist[i]);       /* the output histogram   */

  if (output_format == 1) {
    if (record_bytes == 836) {
      fwrite((char *)hist,    (size_t) record_bytes, (size_t) 1, outfile);
      fwrite((char *)hist+record_bytes, (size_t) length,(size_t) 1,outfile);
    }
    else {
      fwrite((char *)hist,    (size_t) 1024,(size_t) 1,outfile);
      total_bytes = 1024;
    }

    /*  pad out the histogram to a multiple of record bytes */
    if (record_bytes == 836)
      for (i=total_bytes; i<record_bytes*2; i++) fputc(blank,outfile);
    else
      for (i=total_bytes; i<record_bytes; i++) fputc(blank,outfile);
  }

  /*********************************************************************/
  /*                                                                   */
  /* process the encoding histogram                                    */
  /* don't have to byte-swap because DECOMP.C does it for us           */
  /*                                                                   */
  /*********************************************************************/
  if (record_bytes == 836) {
    length = read_var((char *)hist,host);
    length = read_var((char *)hist+836,host);
    length = read_var((char *)hist+1672,host);
  }
  else {
    length = read_var((char *)hist,host);
    length = read_var((char *)hist+1204,host);
  }

  /*********************************************************************/
  /*                                                                   */
  /* process the engineering summary                                   */
  /*                                                                   */
  /*********************************************************************/

  total_bytes = 0;
  length = read_var((char *) ibuf,host);

  if (output_format == 1) {
    fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
    total_bytes = total_bytes + length;

    /*  pad out engineering to multiple of record_bytes */
    for (i=total_bytes;i<record_bytes;i++) fputc(blank,outfile);
  }

  /*********************************************************************/
  /*                                                                   */
  /* process the line header table                                     */
  /*                                                                   */
  /*********************************************************************/

  if (record_bytes == 1204) {
    int_length = 0L;
    for (i=0; i<1056; i++) {
      length = read_var((char *) ibuf,host);
      if (output_format == 1) {
	fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
	int_length = int_length + length;
      }
    }

    /*  pad out engineering to multiple of record_bytes */
    if (output_format == 1)
      for (x=int_length;x<1204L*55L;x++) fputc(blank,outfile);
  }

  /*********************************************************************/
  /*                                                                   */
  /* initialize the decompression                                      */
  /*                                                                   */
  /*********************************************************************/

  if (outfile != stdout)
    fprintf(stderr,"\nInitializing decompression routine...");
  decmpinit(hist);


  /*********************************************************************/
  /*                                                                   */
  /* decompress the image                                              */
  /*                                                                   */
  /*********************************************************************/

  if (outfile!=stdout) fprintf(stderr,"\nDecompressing data...");
  line=0;

  do {
    length = read_var((char *) ibuf,host);
    if (length <= 0) break;
    int_length = (int)length;
    line += 1;
    decompress((char *) ibuf, (char *) obuf, &int_length, &record_bytes);

    if (output_format == 1) {
      count = fwrite(obuf,(size_t) record_bytes,(size_t) 1,outfile);
      if (count != 1) {
	fprintf(stderr,"\nError writing output file.  Aborting program.");
	fprintf(stderr,"\nCheck disk space or for duplicate filename.");
	exit(1);
      }
    }
    else  {
      /* VICAR/FITS/etc */
      count = fwrite(obuf,(size_t) line_samples,(size_t) 1,outfile);
      if (count != 1) {
	fprintf(stderr,"\nError writing output file.  Aborting program.");
	fprintf(stderr,"\nCheck disk space or for duplicate filename.");
	exit(1);
      }
    }

    if (record_bytes == 1204) /* do checksum for viking */
      for (i=0; i<record_bytes; i++) checksum += (int)obuf[i];

    if ((line % 100 == 0) && (outfile != stdout)) 
      fprintf(stderr,"\nline %d",line);

  } while (length > 0 && line < max_lines);

  if (record_bytes == 1204  && (outfile  != stdout)) 
    /* print checksum for viking */
    fprintf(stderr,"\n Image label checksum = %d computed checksum = %d\n",
	    label_checksum,checksum);

  /*  pad out FITS file to a multiple of 2880 */
  if (output_format == 2)
    for (i=0;i<fits_pad;i++) fputc(blank,outfile);

  if (outfile!=stdout) printf("\n");
  free_tree(&int_length);

  close(infile);
  fclose(outfile);

  return 0;
}


/*********************************************************************/
/*                                                                   */
/* subroutine get_files - get input filenames and open               */
/*                                                                   */
/*********************************************************************/

int get_files(host)
int host;
{
  short   shortint;
  typedef long    off_t;

  if (inname[0] == ' ') {
    printf("\nEnter name of file to be decompressed: ");
    fgets (inname, BUFSIZE, stdin);
  }

  if (host == 1 | host == 2) {
    if ((infile = open(inname,O_RDONLY | O_BINARY)) <= 0) {
      fprintf(stderr,"\ncan't open input file: %s\n",inname);
      exit(1);
    }
  }
  else if (host == 3 | host == 5) {
    if ((infile = open(inname,O_RDONLY)) <= 0) {
      fprintf(stderr,"\ncan't open input file: %s\n",inname);
      exit(1);
    }

    /****************************************************************/
    /* If we are on a vax see if the file is in var length format.  */
    /* This logic is in here in case the vax file has been stored   */
    /* in fixed or undefined format.  This might be necessary since */
    /* vax variable length files can't be moved to other computer   */
    /* systems with standard comm programs (kermit, for example).   */
    /****************************************************************/

     if (host == 3) {
       read(infile,&shortint, (size_t) 2);
       if (shortint > 0 && shortint < 80) {
	 host = 4;              /* change host to 4                */
	 printf("This is not a VAX variable length file.");
       }
       else printf("This is a VAX variable length file.");
       lseek(infile,(off_t) 0,0);     /* reposition to beginning of file */
     }
  }

  if (output_format == 0)
    do {
      printf("\nEnter a number for the output format desired:\n");
      printf("\n  1.  SFDU/PDS format.");
      printf("\n  2.  FITS format.");
      printf("\n  3.  VICAR format.");
      printf("\n  4.  Unlabelled binary array.\n");
      printf("\n  Enter format number:");
      fgets(inname,BUFSIZE,stdin);
      output_format = atoi(inname);
    } while (output_format < 1 || output_format > 4);

  if (outname[0] == ' ') {
    printf("\nEnter name of uncompressed output file: ");
    fgets (outname, BUFSIZE, stdin);
  }

  return(host);
}


/*********************************************************************/
/*                                                                   */
/* subroutine open_files - open the output file after we get         */
/*   its record size by reading the input file labels.               */
/*                                                                   */
/*********************************************************************/

void open_files(host)
int *host;
{
  if (*host == 1 || *host == 2 || *host == 5)  {
    if (outname[0] == '-') outfile=stdout;
    else if ((outfile = fopen(outname,"wb"))==NULL) {
      fprintf(stderr,"\ncan't open output file: %s\n",outname);
      exit(1);
    }
  }

  else if (*host == 3 || *host == 4) {
    if (output_format == 1) {     /* write PDS format blocks */
      if (record_bytes == 836) { 
	if ((outfile=fopen(outname,"w"
#ifdef VMS
			   ,"mrs=836",FOP,CTX,RECORD_TYPE
#endif
			   ))==NULL) {
	  fprintf(stderr,"\ncan't open output file: %s\n",outname);
	  exit(1);
	}
      }
      else {
	if ((outfile=fopen(outname,"w"
#ifdef VMS
			   ,"mrs=1204",FOP,CTX,RECORD_TYPE
#endif
			   ))==NULL) {
	  fprintf(stderr,"\ncan't open output file: %s\n",outname);
	  exit(1);
	}
      }
    }
    else if (output_format == 2) {  /* write FITS format blocks */
      if ((outfile=fopen(outname,"w"
#ifdef VMS
			 ,"mrs=2880",FOP,CTX,RECORD_TYPE
#endif
			 ))==NULL) {
	fprintf(stderr,"\ncan't open output file: %s\n",outname);
	exit(1);
      }
    }

    else {                       /* write fixed length records */
      if (record_bytes == 836) { 
	if ((outfile=fopen(outname,"w"
#ifdef VMS
			   ,"mrs=800",FOP,CTX,RECORD_TYPE
#endif
			   ))==NULL) {
	  fprintf(stderr,"\ncan't open output file: %s\n",outname);
	  exit(1);
	}
      }
      else {
	if ((outfile=fopen(outname,"w"
#ifdef VMS
			   ,"mrs=1204",FOP,CTX,RECORD_TYPE
#endif
			   ))==NULL) {
	  fprintf(stderr,"\ncan't open output file: %s\n",outname);
	  exit(1);
	}
      }
    }
  }
}


/*********************************************************************/
/*                                                                   */
/* subroutine pds_labels - edit PDS labels and write to output file  */
/*                                                                   */
/*********************************************************************/

void pds_labels(host)
     int host;
{
  char          outstring[80],ibuf[2048];
  unsigned char cr=13,lf=10,blank=32;
  short         length,nlen,total_bytes,line,i;


  total_bytes = 0;
  do {
    length = read_var(ibuf,host);
    ibuf[length] = '\0';

    /******************************************************************/
    /*  edit labels which need to be changed                          */
    /******************************************************************/

    if      ((i = strncmp(ibuf,"NJPL1I00PDS1",    (size_t) 12)) == 0);
    else if ((i = strncmp(ibuf,"CCSD3ZF00001",    (size_t) 12)) == 0);
    else if ((i = strncmp(ibuf,"/*          FILE",(size_t) 16)) == 0);
    else if ((i = strncmp(ibuf,"RECORD_TYPE",     (size_t) 11)) == 0);

    /*****************************************************************/
    /* don't write any of these labels out until we get the record   */
    /* bytes parameter.                                              */
    /*****************************************************************/

    else if ((i = strncmp(ibuf,"RECORD_BYTES", (size_t) 12)) == 0) {
      /*****************************************************************/
      /* get the record_bytes value                                    */
      /*****************************************************************/

      sscanf(ibuf+35,"%d",&record_bytes);
      if (record_bytes != 836) record_bytes = 1204;
      open_files(&host);

      /* now we can write out the SFDU, comment and Record Type labels. */
      if (record_bytes == 836)
        fwrite("CCSD3ZF0000100000001NJPL3IF0PDS200000001 = SFDU_LABEL",
	       (size_t) 53,(size_t) 1,outfile);
      else
        fwrite("CCSD3ZF0000100000001NJPL3IF0PDS200000001 = SFDU_LABEL",
	       (size_t) 53,(size_t) 1,outfile);      

      fprintf(outfile,"%c%c",cr,lf);
      fwrite("/*          FILE FORMAT AND LENGTH */",(size_t) 37,(size_t) 1,
	     outfile);      
      fprintf(outfile,"%c%c",cr,lf);
      fwrite("RECORD_TYPE                      = FIXED_LENGTH",(size_t) 47,
	     (size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);

      /* fix record_bytes parameter for Viking images */
      if (record_bytes == 1204) strcpy(ibuf+35,"1204");
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 57 + 39 + 49;
    }

    else if ((i = strncmp(ibuf,"FILE_RECORDS",(size_t) 12)) == 0) {
      /*****************************************************************/
      /* change the file_records count                                 */
      /*****************************************************************/

      if (record_bytes == 836) strcpy(ibuf+35,"806");
      else                     strcpy(ibuf+35,"1115");
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    else if ((i = strncmp(ibuf,"LABEL_RECORDS",(size_t) 13)) == 0) {
      /*****************************************************************/
      /* change the label_records count from 56 to 3                   */
      /*****************************************************************/

      if (record_bytes == 836) strcpy(ibuf+35,"3");
      else                     strcpy(ibuf+35,"2");
      length -= 1;
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    else if ((i = strncmp(ibuf,"^IMAGE_HISTOGRAM",(size_t) 16)) == 0) {
      /*****************************************************************/
      /* change the location pointer of image_histogram to record 4    */
      /*****************************************************************/

      if (record_bytes == 836) strcpy(ibuf+35,"4");
      else                     strcpy(ibuf+35,"3");
      length -= 1;
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    else if ((i = strncmp(ibuf,"^ENCODING_HISTOGRAM)",(size_t) 19)) == 0);

    /*****************************************************************/
    /* delete the encoding_histogram location pointer                */
    /*****************************************************************/

    else if ((i = strncmp(ibuf,"^ENGINEERING_TABLE",(size_t) 18)) == 0) {
      /*****************************************************************/
      /* change the location pointer of engineering_summary to record 6*/
      /*****************************************************************/

      if (record_bytes == 836) strcpy(ibuf+35,"6");
      else                     strcpy(ibuf+35,"4");
      length -= 1;
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    else if ((i = strncmp(ibuf,"^LINE_HEADER_TABLE",(size_t) 18)) == 0) {
      /*****************************************************************/
      /* change the location pointer of line header table to record 5  */
      /*****************************************************************/

      strcpy(ibuf+35,"5");
      length -= 1;
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    else if ((i = strncmp(ibuf,"^IMAGE",(size_t) 6)) == 0) {
      /*****************************************************************/
      /* change the location pointer of image to record 7              */
      /*****************************************************************/

      if (record_bytes == 836) {
	strcpy(ibuf+35,"7");
	length=length-1;
      }
      else {
	strcpy(ibuf+35,"60");
	length = length - 2; 
      }

      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }
    else if ((i = strncmp(ibuf,"OBJECT                           = ENCODING",
			  (size_t) 43)) == 0) {

      /*****************************************************************/
      /* delete the 4 encoding histogram labels                        */
      /*****************************************************************/

      for (i=0; i<4; i++) {   /* ignore these labels */
	length = read_var(ibuf,host);
      }
    }

    else if ((i = strncmp(ibuf," ENCODING",(size_t) 9)) == 0);
    
    /*****************************************************************/
    /* delete the encoding type label in the image object            */
    /*****************************************************************/

    else if ((host == 2 || host == 5) && (i = strncmp(ibuf,
             " ITEM_TYPE                       = VAX_INTEGER",
						      (size_t) 46)) == 0) {
      /*****************************************************************/
      /* change the record_type value from variable to fixed           */
      /*****************************************************************/

      strcpy(ibuf+35,"INTEGER");
      length = length - 4;
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    /*****************************************************************/
    /* find the checksum and store in label_checksum                 */
    /*****************************************************************/
    else if ((i = strncmp(ibuf," CHECKSUM",(size_t) 9)) == 0) {
      ibuf[length]   = '\0';
      label_checksum = atol(ibuf+35);
    }

    /*****************************************************************/
    /* if none of above write out the label to the output file       */
    /*****************************************************************/
    else {
      fwrite(ibuf,(size_t) length,(size_t) 1,outfile);
      fprintf(outfile,"%c%c",cr,lf);
      total_bytes = total_bytes + length + 2;
    }

    /*****************************************************************/
    /* test for the end of the PDS labels                            */
    /*****************************************************************/
    if ((i = strncmp(ibuf,"END",(size_t) 3)) == 0 && length == 3) break;
  } while (length > 0);

  /* pad out the labels with blanks to multiple of record_bytes */
  if (record_bytes == 836)
    for (i=total_bytes; i<record_bytes*3; i++) fputc(blank,outfile);
  else
    for (i=total_bytes; i<record_bytes*2; i++) fputc(blank,outfile);
}


/*********************************************************************/
/*                                                                   */
/* subroutine fits_labels - write FITS header to output file */
/*                                                                   */
/*********************************************************************/

void fits_labels(host)
int host;
{
  char          ibuf[2048],outstring[80];
  short         length,nlen,total_bytes,line,i;
  unsigned char cr=13,lf=10,blank=32;

  do {
    length = read_var(ibuf,host);

    /*****************************************************************/
    /* find the checksum and store in label_checksum                 */
    /*****************************************************************/
    if ((i = strncmp(ibuf," CHECKSUM",(size_t) 9)) == 0) { 
      ibuf[length]   = '\0';
      label_checksum = atol(ibuf+35);
    }

    else if ((i = strncmp(ibuf,"RECORD_BYTES",(size_t) 12)) == 0) {
      /*****************************************************************/
      /* get the record_bytes value                                    */
      /*****************************************************************/

      sscanf(ibuf+35,"%d",&record_bytes);
      if (record_bytes != 836) record_bytes = 1204;
    }

    /*****************************************************************/
    /* read to the end of the PDS labels                             */
    /*****************************************************************/
    if ((i = strncmp(ibuf,"END",(size_t) 3)) == 0 && length == 3) break;
  } while (length > 0);

  open_files(&host);
  total_bytes = 0;

  strcpy(outstring,"SIMPLE  =                    T");
  strcat(outstring,"                                               ");
  fwrite(outstring,(size_t) 78,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 80;

  strcpy(outstring,"BITPIX  =                    8");
  strcat(outstring,"                                               ");
  fwrite(outstring,(size_t) 78,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 80;

  strcpy(outstring,"NAXIS   =                    2");
  strcat(outstring,"                                               ");
  fwrite(outstring,(size_t) 78,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 80;

  if (record_bytes == 836)
    strcpy(outstring,"NAXIS1  =                  800");
  else 
    strcpy(outstring,"NAXIS1  =                 1204");

  strcat(outstring,"                                               ");
  fwrite(outstring,(size_t) 78,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 80;

  if (record_bytes == 836)
    strcpy(outstring,"NAXIS2  =                  800");
  else
    strcpy(outstring,"NAXIS2  =                 1056");

  strcat(outstring,"                                               ");
  fwrite(outstring,(size_t) 78,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 80;

  strcpy(outstring,"END                             ");
  strcat(outstring,"                                               ");
  
  fwrite(outstring,(size_t) 78,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 80;

  /* pad out the labels with blanks to multiple of 2880 for FITS */
  for (i=total_bytes; i<2880; i++) fputc(blank,outfile);
}

/*********************************************************************/
/*                                                                   */
/* subroutine vicar_labels - write vicar labels to output file       */
/*                                                                   */
/*********************************************************************/

void vicar_labels(host)
int host;

{
  char          ibuf[2048],outstring[80];
  short         length,nlen,total_bytes,line,i;
  unsigned char cr=13,lf=10,blank=32;

  do {
    length = read_var(ibuf,host);
    /*****************************************************************/
    /* find the checksum and store in label_checksum                 */
    /*****************************************************************/
    if ((i = strncmp(ibuf," CHECKSUM",(size_t) 9)) == 0) { 
      ibuf[length]   = '\0';
      label_checksum = atol(ibuf+35);
    }

    else if ((i = strncmp(ibuf,"RECORD_BYTES",(size_t) 12)) == 0) {
      /*****************************************************************/
      /* get the record_bytes value                                    */
      /*****************************************************************/

      sscanf(ibuf+35,"%d",&record_bytes);
      if (record_bytes != 836) record_bytes = 1204;
    }

    /*****************************************************************/
    /* read to the end of the PDS labels                             */
    /*****************************************************************/
    if ((i = strncmp(ibuf,"END",(size_t) 3)) == 0 && length == 3) break;
  } while (length > 0);

  open_files(&host);
  total_bytes = 0;

  if (record_bytes == 836)
    strcpy(outstring,
  "LBLSIZE=800             FORMAT='BYTE'  TYPE='IMAGE'  BUFSIZ=800  DIM=2  ");

  else
    strcpy(outstring,
  "LBLSIZE=1204            FORMAT='BYTE'  TYPE='IMAGE'  BUFSIZ=1204 DIM=2  ");

  fwrite(outstring,(size_t) 72,(size_t) 1,outfile);
  total_bytes = total_bytes + 72;

  if (record_bytes == 836)
    strcpy(outstring,
  "EOL=0  RECSIZE=800  ORG='BSQ'  NL=800  NS=800  NB=1  N1=0  N2=0  N3=0  ");
  else
    strcpy(outstring,
  "EOL=0  RECSIZE=1204 ORG='BSQ'  NL=1056 NS=1204 NB=1  N1=0  N2=0  N3=0  ");

  total_bytes = total_bytes + 71;
  fwrite(outstring,(size_t) 71,(size_t) 1,outfile);
  strcpy(outstring,"N4=0  NBB=0  NLB=0");
  fwrite(outstring,(size_t) 18,(size_t) 1,outfile);
  fprintf(outfile,"%c%c",cr,lf);
  total_bytes = total_bytes + 20;

  /* pad out the labels with blanks to multiple of record_bytes        */
  for (i=total_bytes;i<record_bytes;i++) fputc(blank,outfile);
}


/*********************************************************************/
/*                                                                   */
/* subroutine no_labels - read past the pds labels                   */
/*                                                                   */
/*********************************************************************/

void no_labels(host)
int host;
{
  char          ibuf[2048],outstring[80];
  short         length,nlen,total_bytes,line,i;

  do {
    length = read_var(ibuf,host);

    /*****************************************************************/
    /* find the checksum and store in label_checksum                 */
    /*****************************************************************/
    if ((i = strncmp(ibuf," CHECKSUM",(size_t) 9)) == 0) { 
      ibuf[length]   = '\0';
      label_checksum = atol(ibuf+35);
    }

    else if ((i = strncmp(ibuf,"RECORD_BYTES",(size_t) 12)) == 0) {
      /*****************************************************************/
      /* get the record_bytes value                                    */
      /*****************************************************************/

      sscanf(ibuf+35,"%d",&record_bytes);
      if (record_bytes != 836) record_bytes = 1204;
    }

    /*****************************************************************/
    /* read to the end of the PDS labels                             */
    /*****************************************************************/
    if ((i = strncmp(ibuf,"END",(size_t) 3)) == 0 && length == 3) break;
  } while (length > 0);

  open_files(&host);
}

/*********************************************************************/
/*                                                                   */
/* subroutine read_var - read variable length records from input file*/
/*                                                                   */
/*********************************************************************/

int read_var(ibuf,host)
char  *ibuf;
int   host;
{
  int   length,result,nlen;
  char  temp;
  union /* this union is used to swap 16 and 32 bit integers          */
    {
      char  ichar[4];
      short slen;
      int  llen;
    } onion;

  switch (host) {
  case 1: /*******************************************************/
          /* IBM PC host                                         */
          /*******************************************************/
    length = 0;
    result = read(infile,&length,(size_t) 2);
    nlen =   read(infile,ibuf,(size_t) (length+(length%2)));
    return (length);

  case 2: /*******************************************************/
          /* Macintosh host                                      */
          /*******************************************************/

    length = 0;
    result = read(infile,onion.ichar,(size_t) 2);
    /*     byte swap the length field                            */
    temp   = onion.ichar[0];
    onion.ichar[0]=onion.ichar[1];
    onion.ichar[1]=temp;
    length = onion.slen;       /* left out of earlier versions   */
    nlen =   read(infile,ibuf,(size_t) length+(length%2));
    return (length);

  case 3: /*******************************************************/
          /* VAX host with variable length support               */
          /*******************************************************/
    length = read(infile,ibuf,(size_t) 2048/* upper bound */);
    return (length);

  case 4: /*******************************************************/
          /* VAX host, but not a variable length file            */
          /*******************************************************/
    length = 0;
    result = read(infile,&length,(size_t) 2);
    nlen =   read(infile,ibuf,(size_t) length+(length%2));

    /* check to see if we crossed a vax record boundary          */
    while (nlen < length)
      nlen += read(infile,ibuf+nlen,(size_t) length+(length%2)-nlen);
    return (length);

  case 5: /*******************************************************/
          /* Unix workstation host (non-byte-swapped 32 bit host)*/
          /*******************************************************/
    length = 0;
    result = read(infile,onion.ichar,(size_t) 2);
    /*     byte swap the length field                            */
    temp   = onion.ichar[0];
    onion.ichar[0]=onion.ichar[1];
    onion.ichar[1]=temp;
    length = onion.slen;
    nlen =   read(infile,ibuf,(size_t) length+(length%2));
    return (length);
  }

  return 0;
}

/*********************************************************************/
/*                                                                   */
/* subroutine check_host - find out what kind of machine we are on   */
/*                                                                   */
/*********************************************************************/

int check_host()
{
  /*  This subroutine checks the attributes of the host computer and
      returns a host code number.
      */
  char hostname[80];

  int swap,host,bits,var;
  union
    {
      char  ichar[2];
      short ilen;
    } onion;

  host = 0;

  if (sizeof(var) == 4) bits = 32;
  else bits = 16;

  onion.ichar[0] = 1;
  onion.ichar[1] = 0;

  if (onion.ilen == 1) swap = TRUE;
  else                 swap = FALSE;

  if (bits == 16 && swap == TRUE ) {
    host = 1; /* IBM PC host  */
    strcpy(hostname,
	   "Host 1 - 16 bit integers with swapping, no var len support.");
  }

  if (bits == 16 && swap == FALSE ) {
    host = 2; /* Non byte swapped 16 bit host  */
    strcpy(hostname,
	   "Host 2 - 16 bit integers without swapping, no var len support.");
  }

  if (bits == 32 && swap == TRUE ) {
    host = 3; /* VAX host with var length support */
    strcpy(hostname,"Host 3,4 - 32 bit integers with swapping.");
 }

  if (bits == 32 && swap == FALSE  ) {
    host = 5; /* OTHER 32-bit host  */
    strcpy(hostname,
	   "Host 5 - 32 bit integers without swapping, no var len support.");
  }

  if ((*outname)!='-') fprintf(stderr,"%s\n",hostname);
  return(host);
}


int swap_int(inval)  /* swap 4 byte integer                       */
     int inval;
{
  union /* this union is used to swap 16 and 32 bit integers          */
    {
      char  ichar[4];
      short slen;
      int   llen;
    } onion;
  char   temp;
  
  /* byte swap the input field                                      */
  onion.llen   = inval;
  temp   = onion.ichar[0];
  onion.ichar[0]=onion.ichar[3];
  onion.ichar[3]=temp;
  temp   = onion.ichar[1];
  onion.ichar[1]=onion.ichar[2];
  onion.ichar[2]=temp;
  return (onion.llen);
}

void decompress(ibuf,obuf,nin,nout)
/****************************************************************************
*_TITLE decompress - decompresses image lines stored in compressed format   *
*_ARGS  TYPE       NAME      I/O        DESCRIPTION                         */
        char *ibuf;        /* I         Compressed data buffer              */
        char *obuf;        /* O         Decompressed image line             */
        int       *nin;   /* I         Number of bytes on input buffer     */
        int       *nout;  /* I         Number of bytes in output buffer    */

{
  /* The external root pointer to tree */
  extern NODE *tree;

  dcmprs(ibuf,obuf,nin,nout,tree);
  
  return;
}


void decmpinit(hist)
/***************************************************************************
*_TITLE decmpinit - initializes the Huffman tree                           *
*_ARGS  TYPE       NAME      I/O        DESCRIPTION                        */
        int      *hist;  /* I         First-difference histogram.        */

{
  extern NODE *tree;          /* Huffman tree root pointer */
  tree = huff_tree(hist);
  return;
}


NODE *huff_tree(hist)
/****************************************************************************
*_TITLE huff_tree - constructs the Huffman tree; returns pointer to root    *
*_ARGS  TYPE          NAME        I/O   DESCRIPTION                         */
        int     *hist;     /* I    First difference histogram          */

{
  /*  Local variables used */
  int freq_list[512];      /* Histogram frequency list */
  NODE **node_list;             /* DN pointer array list */

  int   *fp;        /* Frequency list pointer */
  NODE **np;        /* Node list pointer */

  int num_freq;   /* Number non-zero frequencies in histogram */
  int sum;                 /* Sum of all frequencies */

  short int num_nodes; /* Counter for DN initialization */
  short int cnt;       /* Miscellaneous counter */

  short int znull = -1;         /* Null node value */

  NODE *temp;          /* Temporary node pointer */


  /**************************************************************************
    Allocate the array of nodes from memory and initialize these with numbers
    corresponding with the frequency list.  There are only 511 possible
    permutations of first difference histograms.  There are 512 allocated
    here to adhere to the FORTRAN version.
   **************************************************************************/

  fp = freq_list;
  node_list = (NODE **) malloc(sizeof(temp) * 512);
  if (node_list == NULL) {
    fprintf(stderr,"\nOut of memory in huff_tree!\n");
    exit(1);
  }
  np = node_list;

  for (num_nodes=1, cnt=512 ; cnt-- ; num_nodes++) {

    /***********************************************************************
      The following code has been added to standardize the VAX byte order
      for the "int" type.  This code is intended to make the routine
      as machine independant as possible.
      **********************************************************************/

    unsigned char *cp = (unsigned char *) hist++;
    unsigned int j;
    short int i;

    j = 0;
    for (i=4 ; --i >= 0 ; j = (j << 8) | *(cp+i));
    
    /* Now make the assignment */
    *fp++ = j;
    temp = new_node(num_nodes);
    *np++ = temp;
  }

  (*--fp) = 0;         /* Ensure the last element is zeroed out.  */

  /*************************************************************************
    Now, sort the frequency list and eliminate all frequencies of zero.
   *************************************************************************/

  num_freq = 512;
  sort_freq(freq_list,node_list,num_freq);

  fp = freq_list;
  np = node_list;

  for (num_freq=512 ; (*fp) == 0 && (num_freq) ; fp++, np++, num_freq--);

  /*************************************************************************
    Now create the tree.  Note that if there is only one difference value,
    it is returned as the root.  On each interation, a new node is created
    and the least frequently occurring difference is assigned to the right
    pointer and the next least frequency to the left pointer.  The node
    assigned to the left pointer now becomes the combination of the two
    nodes and it's frequency is the sum of the two combining nodes.
   *************************************************************************/

  for (temp=(*np) ; (num_freq--) > 1 ; ) {
    temp = new_node(znull);
    temp->right = (*np++);
    temp->left = (*np);
    *np = temp;
    *(fp+1) = *(fp+1) + *fp;
    *fp++ = 0;
    sort_freq(fp,np,num_freq);
  }

  return temp;
}


NODE *new_node(value)
/****************************************************************************
*_TITLE new_node - allocates a NODE structure and returns a pointer to it   *
*_ARGS  TYPE        NAME        I/O     DESCRIPTION                         */
        int         value;    /* I      Value to assign to DN field         */

{
  NODE *temp;         /* Pointer to the memory block */

  /************************************************************************
    Allocate the memory and intialize the fields.
   ************************************************************************/

  temp = (NODE *) malloc(sizeof(NODE));

  if (temp != NULL) {
    temp->right = NULL;
    temp->dn = (short int) value;
    temp->left = NULL;
  }
  else {
    fprintf(stderr,"\nOut of memory in new_node!\n");
    exit(1);
  }

  return temp;
}

void sort_freq(freq_list,node_list,num_freq)
/****************************************************************************
*_TITLE sort_freq - sorts frequency and node lists in increasing freq. order*
*_ARGS  TYPE       NAME            I/O  DESCRIPTION                         */
        int        *freq_list;   /* I   Pointer to frequency list           */
        NODE       **node_list;  /* I   Pointer to array of node pointers   */
        int        num_freq;     /* I   Number of values in freq list       */

{
  /* Local Variables */
   int *i;       /* primary pointer into freq_list */
   int *j;       /* secondary pointer into freq_list */

   NODE **k;          /* primary pointer to node_list */
   NODE **l;          /* secondary pointer into node_list */

  int temp1;             /* temporary storage for freq_list */
  NODE *temp2;                /* temporary storage for node_list */

   int cnt;      /* count of list elements */

  /*********************************************************************
    Save the current element - starting with the second - in temporary
    storage.  Compare with all elements in first part of list moving
    each up one element until the element is larger.  Insert current
    element at this point in list.
   *********************************************************************/

  if (num_freq <= 0) return;      /* If no elements or invalid, return */

  for (i=freq_list, k=node_list, cnt=num_freq ; --cnt ; *j=temp1, *l=temp2) {
    temp1 = *(++i);
    temp2 = *(++k);

    for (j = i, l = k ;  *(j-1) > temp1 ; ) {
      *j = *(j-1);
      *l = *(l-1);
      j--;
      l--;
      if ( j <= freq_list) break;
    }
    
  }
  return;
}


void dcmprs(ibuf,obuf,nin,nout,root)
/****************************************************************************
*_TITLE dcmprs - decompresses Huffman coded compressed image lines          *
*_ARGS  TYPE       NAME       I/O       DESCRIPTION                         */
        char       *ibuf;   /* I        Compressed data buffer              */
        char       *obuf;   /* O        Decompressed image line             */
        int        *nin;    /* I        Number of bytes on input buffer     */
        int        *nout;   /* I        Number of bytes in output buffer    */
        NODE       *root;   /* I        Huffman coded tree                  */

{
  /* Local Variables */
  NODE *ptr = root;        /* pointer to position in tree */
  unsigned char test;      /* test byte for bit set */
  unsigned char idn;       /* input compressed byte */
  
  char odn;                /* last dn value decompressed */
  
  char *ilim = ibuf + *nin;         /* end of compressed bytes */
  char *olim = obuf + *nout;        /* end of output buffer */

  /**************************************************************************
    Check for valid input values for nin, nout and make initial assignments.
   **************************************************************************/

  if (ilim > ibuf && olim > obuf)
    odn = *obuf++ = *ibuf++;
  else {
    fprintf(stderr,"\nInvalid byte count in dcmprs!\n");
    exit(1);
  }

  /************************************************************************
    Decompress the input buffer.  Assign the first byte to the working
    variable, idn.  An arithmatic and (&) is performed using the variable
    'test' that is bit shifted to the right.  If the result is 0, then
    go to right else go to left.
   ************************************************************************/

  for (idn=(*ibuf) ; ibuf < ilim  ; idn =(*++ibuf)) {
    for (test=0x80 ; test ; test >>= 1) {
      ptr = (test & idn) ? ptr->left : ptr->right;

      if (ptr->dn != -1)  {
	if (obuf >= olim) return;
	odn -= ptr->dn + 256;
	*obuf++ = odn;
	ptr = root;
      }
    }
  }
  return;
}


void free_tree(nfreed)
/****************************************************************************
*_TITLE free_tree - free memory of all allocated nodes                      *
*_ARGS  TYPE       NAME       I/O        DESCRIPTION                        */
        int      *nfreed;  /* O        Return of total count of nodes     *
*                                        freed.                             */

/*
*_DESCR This routine is supplied to the programmer to free up all the       *
*       allocated memory required to build the huffman tree.  The count     *
*       of the nodes freed is returned in the parameter 'nfreed'.  The      *
*       purpose of the routine is so if the user wishes to decompress more  *
*       than one file per run, the program will not keep allocating new     *
*       memory without first deallocating all previous nodes associated     *
*       with the previous file decompression.                               *

*_HIST  16-AUG-89 Kris Becker   USGS, Flagstaff Original Version            *
*_END                                                                       *
****************************************************************************/

{
  int total_free = 0;

  extern NODE *tree;      /* Huffman tree root pointer */

  *nfreed = free_node(tree,total_free);

  return;
}


int free_node(pnode,total_free)
/***************************************************************************
*_TITLE free_node - deallocates an allocated NODE pointer
*_ARGS  TYPE     NAME          I/O   DESCRIPTION                           */
        NODE     *pnode;       /* I  Pointer to node to free               */
        int       total_free;   /* I  Total number of freed nodes           */

/*
*_DESCR  free_node will check both right and left pointers of a node       *
*        and then free the current node using the free() C utility.        *
*        Note that all nodes attached to the node via right or left        *
*        pointers area also freed, so be sure that this is the desired     *
*        result when calling this routine.                                 *

*        This routine is supplied to allow successive calls to the         *
*        decmpinit routine.  It will free up the memory allocated          *
*        by previous calls to the decmpinit routine.  The call to free     *
*        a previous huffman tree is:  total = free_node(tree,(int) 0);    *
*        This call must be done by the programmer application routine      *
*        and is not done by any of these routines.                         *
*_HIST   16-AUG-89  Kris Becker U.S.G.S  Flagstaff Original Version        */
{
  if (pnode == (NODE *) NULL) return(total_free);
  
  if (pnode->right != (NODE *) NULL)
    total_free = free_node(pnode->right,total_free);
  if (pnode->left != (NODE *) NULL)
    total_free = free_node(pnode->left,total_free);
  
  free((char *) pnode);
  return(total_free + 1);
}